initWithNibName vs init - 意外行为

时间:2013-08-04 18:11:03

标签: ios objective-c cocoa-touch nib

我注意到添加带有界面构建器和nib的viewController时,

我不必调用initWithNibName来获取相关的nib,我只能调用init!

知道为什么吗?

此:

NotificationManagementController *notificationView = [[NotificationManagementController alloc] initWithNibName:@"NotificationManagementController" bundle:nil andCurrentNotifications:nil];

和这:

NotificationManagementController *notificationView = [[NotificationManagementController alloc] init];

两者似乎都可以互换......

因此,如果我然后调用这些代码行:

notificationView.delegate = self;
notificationView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:notificationView animated:YES completion:NULL];

我看到了笔尖的所有变化。

1 个答案:

答案 0 :(得分:2)

NotificationManagementController *notificationView = [[NotificationManagementController alloc] initWithNibName:@"NotificationManagementController" bundle:nil andCurrentNotifications:nil];

根本不是必要的,甚至有些人(包括我)不满意。

NotificationManagementController *notificationView = [[NotificationManagementController alloc] init];

更清晰(更安全),隐藏了实现细节,但会在幕后有效地调用initWithNibName:

我喜欢这样想:

- (id)init 
{
    self = [[NotificationManagementController alloc] initWithNibName:@"NotificationManagementController" bundle:nil andCurrentNotifications:nil];
    if (self)
    {
        // Initialization
    }
    return self;
}