rustybeanstalk
rustybeanstalk

Reputation: 2762

How to instantiate a UIViewController subclass from a xib?

I have a UIViewController with a UIView in interface builder. I can not for the life of me get it instantiated properly.

I am using:

LoginViewController* myViewController = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil] self.window.rootViewController = myViewController;

Any help? Thanks in advance.

Upvotes: 1

Views: 3074

Answers (2)

From the lines you have supplied, it seems that the instantiation is being done correctly. Aren't you forgetting to add the myViewControllers view to the window? Like this: [self.window addSubView:myViewController.view]

Upvotes: 2

eric.mitchell
eric.mitchell

Reputation: 8855

It shouldn't be one line like the way you have it, and you are forgetting one step; try:

LoginViewController* controller = [[[LoginViewController alloc]
    initWithNibName:@"LoginViewController" bundle:nil] autorelease];

self.window.rootViewController = controller;
[self.window makeKeyAndVisible];

It is autoreleased so that you don't have to manually release it, and that reference to the object will be released once it is no longer needed. Also, specifying the nib name is optional as long as the nib name is the same as the name of the view controller, which it appears to be in this case. So, you could really just do:

LoginViewController* controller = [[[LoginViewController alloc] init] autorelease];

self.window.rootViewController = controller;
[self.window makeKeyAndVisible];

Upvotes: 1

Related Questions