Importing an existing Object in Objective C
How does one use an already existing object from ano开发者_JS百科ther class?
e.g. Have a object of Class1 and want to set its variables from Class2.
What does one import? Is it just necessary to import the Class1, will this make the object available to the class that imported?
In a class e.g. Main Class1 is created and presented
- (IBAction) openClass1 {
Class1 *c = [[Class1 alloc]initWithNibName:@"Class1" bundle:nil];
[self presentModalViewController:c animated:NO];
[c release];
}
Then Class1 would have many properties (I only made one here)
@interface Class1 : UIViewController {
UIImageView *image;
}
@property(nonatomic, retain) UIImageView *image;
@end
I would like to edit the Class1 variables in Class2 and then dismiss the Class2 view and see the changes in Class1. e.g. a label with new text or a UIImage with another image set to it etc.
What you have here is actually view controller classes. You should not assume that another view controller has it's view loaded. A view controller should be allowed to load it's view lazily and as needed, this is a core concept of Cocoa Touch.
This means you should not access a view controllers view or subviews (like UILabel
s, and UIImageView
s) directly from the outside.
If you want to configure a a view controller to be displayed, they you should probably do that using the designated initializer.
You could for example create Class1
like this:
@interface Class1 : UIViewController {
UIImage* imageToShow;
IBOutlet UIImageView* imageView;
}
-(id)initWithImage:(UIImage*)image;
@end
And implement it like this:
@implementation Class1
- (id)initWithImage:(UIImage*)image {
self = [self initWithNibNamed:@"Class1" bundle:nil];
if (self) {
imageToShow = [image retain];
}
return self;
}
- (void)dealloc {
[imageToShow release];
[super dealloc];
}
- (void)viewDidLoad;
imageView.image = imageToShow;
}
@end
And then from Class2
you present the view controller Class1
like so:
-(IBAction) openClass1 {
Class1 *c = [[Class1 alloc] initWithImage:[UIImage imageNamed:@"Test.png"]];
[self presentModalViewController:c animated:NO];
[c release];
}
Look again at this line:
Class1 *c = [[Class1 alloc]initWithNibName:@"Class1" bundle:nil];
So what that does is create an instance of Class1. This is a new instance, freshly initialized. And c is a pointer to that new instance.
So once you have c, you can send c message or access c's properties. In your example, you can do something like this right after the line above:
c.image = [UIImage imageNamed:@"foo.png"];
And you'll also want to import "Class1.h" so that the compiler is satisfied that Class1 does in fact have a property called 'image'.
It's important to understand, though, what's going on here. You're not importing an object. You're creating an object, an instance of Class1. And then to convince the compiler that it is OK to set that property, you import Class1.h which tells the compiler about all of the @property's and public methods.
精彩评论