且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么时候应该使用 initWithNibName 初始化视图控制器?

更新时间:2023-11-11 15:43:10

-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.