查看控制器初始化

时间:2014-12-06 05:29:02

标签: ios objective-c

通常,视图控制器在Application Delegate中初始化,如下所示:

- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch
    TestViewController *VC = [[TestViewController alloc] **init**];
    self.window.rootViewController = VC;
    return YES;
}

但是VC会实现像- (instancetype)initWithNibName:这样的初始化方法。

init如何致电initWithNibName:?呼叫顺序是什么?

1 个答案:

答案 0 :(得分:0)

如果查看默认实现,它只需调用超类的版本:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

不需要实现initWithNibName,因为默认的init方法会为您调用initWithNibName:nibNameOrNil的超级实现。

如果您仅使用代码创建TestViewController(无xibs),则您发布的代码是可以接受的。否则,您应该调用initWithNibName并传递要用于该视图控制器的笔尖名称。