iphone sdk initWithNibName被多次调用

时间:2011-04-19 21:30:17

标签: objective-c cocoa-touch uiviewcontroller

我试图通过指定名称来动态加载视图控制器,但问题是initWithNibName方法被调用两次,所以我不能依赖它来进行初始化。这是一个深夜,所以我可能会错过一些东西。下面是我用来加载控制器的代码,也许你会在这里发现错误:

/*
 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;
}

感谢您的想法

1 个答案:

答案 0 :(得分:2)

是的,是的。

这是你的问题:

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

+newalloc / init的同义词。 -[UIViewController init]只需使用-initWithNibName:bundle:作为两个参数调用nil。然后你自己调用它。

换句话说,你正在初始化你的对象两次,这是一个大禁忌。这就是你想要的:

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