the ViewController in MVC, in XCode
a quick question,
I have been dabbling with XCode off late and am trying to understand the View Controller, while I get the nitty gritty of it, one thing I fail to see is where the View Controller class o开发者_StackOverflow中文版bject is instantiated. It is, in essence a class and hence has to have an object instantiated to be able to send messages to it.
It's kind of left me scratching my head.
Thanks much!
It is instantiated whenever it needs to be displayed. By you.
For example, if you wanted to display a new view on the navigation stack on the press of a button?
-(IBAction)buttonClicked:(id)sender{
/* Create VC here */
YourViewController *controller = [[YourViewController alloc]initWithNibName:@"ViewName"];
/* Push */
[self.navigationController pushViewController:controller animated:YES];
/* Let go since you don't have control over it anymore. */
[controller release];
}
I believe it is generally better to do this instead of holding an instance in memory in most situations, to prevent too much memory usage.
Now (assuming iOS5 is out of NDA now that most of it has been announced today), you can use Storyboarding in XCode that will handle all this for you.
The view controller is instantiated in it's init function designated initializer being the following:
-(id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
if( (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) )
{
// Custom initialization
}
return self;
}
As you will perhaps have noted in some of Apples examples or any other source code you've looked through you might have seen a line of code similar to
MyViewController* viewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
This is where/when the view controller gets instantiated. You'll notice that a view controller has a member object of type UIView called view it is this that gets added to the window or view that this view is to be apart of. The view controller is created to handle messages pertaining to this view. It's all spelled out here.
精彩评论