Inserting subView - iPhone
- (void)viewDidLoad {
BlueViewController *blueController = [[BlueViewController alloc] initWithNibName@"BlueView" bundle:nil];
self.blueViewController = blueController; //blueViewController set to var above
[self.view insertSubview:blueController.view atIndex:0];
[blueController release];
[super viewDidLoad];
}
not understanding this code very well. How c开发者_如何学编程ome i am inserting the subview blueController and not self.blueViewController
also what difference does it make if I don't use self. Not even sure why self is used. I interpret it as I am setting the blueViewController property of the current View Controller to the blueController instance but why would I do that. The book I am reading from does not explain such things in detail. It is pretty much monkey do this.
not understanding this code very well. How come i am inserting the subview blueController and not self.blueViewController
since you have executed the assignment:
self.blueViewController = blueController;
those two variables are the same, so
[self.view insertSubview:self.blueController.view atIndex:0];
would be just the same as the code you posted.
also what difference does it make if I don't use self. Not even sure why self is used. I interpret it as I am setting the blueViewController property of the current View Controller to the blueController instance but why would I do that. The book I am reading from does not explain such things in detail. It is pretty much monkey do this.
if you don't assign to self.blueController
, then your variable is just a simple variable local to that function. By having a property self.blueController
and storing there a value, you can use that value in all of the selectors (functions) of your class.
check the code and you will see that self.blueController
is used also in other functions. e.g., at some point you might decide you like making that subview hidden, or you want to remove it, etc. All of this you can do only if you have a pointer to the controller accessible to your class functions.
self is used if you are referring to an object of the class.
While initializing a variable we must use self. This will increment blueViewController retainCount to 1.
self.blueViewController = blueController;
While inserting also you can use both. Results will be same.
[self.view insertSubview:blueController.view atIndex:0];
[self.view insertSubview:self.blueController.view atIndex:0];
blueController is an alloced and initialized object while blueViewController is just a pointer to the BlueViewController class.By writing
self.blueViewController = blueController
you retain the blueController object.If you do not use self you won't be ratining the object and after you release it at line
[blueController release];
your program will crash as soon as you refer to it again.
精彩评论