Marius
Marius

Reputation: 4016

iphone sdk initWithNibName gets called multiple times

I'm trying to load view controllers dynamically just by specifying their names, but the problem is the initWithNibName method gets called twice so i can't rely on it to do initializations. It's a late night so i might just be missing something. Below is the code i use to load the controller, maybe you'll spot the error here:

/*
 Loads a view from a nib file. The parameter of this method is a nib name 
 withoug an extension (eg. MyView). A controller for the view must exist
 with the same name + "Controller" (eg. MyViewController)
 */
+(UIViewController *)loadViewFromNib:(NSString *)nibName
{
    // Try to create an object by class name
    // We need this so that the controller-specific overriden methods could be called
    Class ctrlClass = NSClassFromString([nibName stringByAppendingString:@"Controller"]);
    NSObject *customctrl = [ctrlClass new];
    UIViewController *ctrl = (UIViewController *)customctrl;
    // Init the controller
    [ctrl initWithNibName:nibName bundle:nil];
    [[ctrl view] setHidden:NO];
    [ctrl autorelease];
    return ctrl;
}

Thank you for your thoughts

Upvotes: 0

Views: 833

Answers (1)

Dave DeLong
Dave DeLong

Reputation: 243156

Yep, it is.

This is your problem:

NSObject *customctrl = [ctrlClass new];
UIViewController *ctrl = (UIViewController *)customctrl;
[ctrl initWithNibName:nibName bundle:nil];

+new is a synonym for alloc/init. -[UIViewController init] simply calls -initWithNibName:bundle: with nil as both arguments. You're then calling it yourself.

In other words, you're initializing your object twice, which is a BIG no-no. Here's what you want instead:

UIViewController *ctrl = [[ctrlClass alloc] initWithNibName:nibName bundle:nil];

Upvotes: 2

Related Questions