我应该何时使用initWithNibName初始化视图控制器? [英] When should I initialize a view controller using initWithNibName?

查看:149
本文介绍了我应该何时使用initWithNibName初始化视图控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该何时使用 init:我何时应该在创建视图控制器时使用 initWithNibName:bundle:

When should I use init: and when should I use initWithNibName:bundle: when creating a view controller?

推荐答案

-initWithNibName:bundle:是UIViewController的指定初始值设定项。最终应该有所谓。也就是说,尽管有Apple的例子(在许多情况下有利于简洁性,但在视图控制器本身之外永远不会调用它)。

-initWithNibName:bundle: is the designated initializer for UIViewController. Something should eventually call it. That said, and despite Apple's examples (which favor brevity over maintainability in many cases), it should never be called from outside the view controller itself.

您经常会看到代码像这样:

You will often see code like this:

MYViewController *vc = [[MYViewController alloc] initWithNibName:@"Myview" bundle:nil];

我说这是不正确的。它将实现细节(NIB的名称和甚至使用NIB的事实)放入调用者。这破坏了封装。正确的方法是:

I say this is incorrect. It puts implementation details (the name of the NIB and the fact that a NIB is even used) into the caller. That breaks encapsulation. The correct way to do this is:

MYViewController *vc = [[MYViewController alloc] init];

然后,在MYViewController中:

Then, in MYViewController:

- (instancetype)init
{
   self = [super initWithNibName:@"Myview" bundle:nil];
   if (self != nil)
   {
       // Further initialization if needed
   }
   return self;
}

- (instancetype)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle
{
    NSAssert(NO, @"Initialize with -init");
    return nil;
}

这会将关键实现细节移回对象,并防止来电者意外打破封装。现在,如果您更改NIB的名称,或者转到编程构造,则可以将其固定在一个位置(在视图控制器中),而不是在使用视图控制器的每个位置。

This moves the key implementation details back into the object, and prevents callers from accidentally breaking encapsulation. Now if you change the name of the NIB, or move to programmatic construction, you fix it in one place (in the view controller) rather than in every place the view controller is used.

这篇关于我应该何时使用initWithNibName初始化视图控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆