使用loadView时无限循环

For*_*est 5 loadview ios

在UIViewController中使用loadView时非常有趣的问题.

通常我们这样使用

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
    NSLog(@"loadview");
    [super loadView];
}
Run Code Online (Sandbox Code Playgroud)

如果删除

 [super loadView];
Run Code Online (Sandbox Code Playgroud)

我们将得到这个死循环

- (void)loadView {
    NSLog(@"loadview");

}
Run Code Online (Sandbox Code Playgroud)

为什么?

Jle*_*xyc 9

在这种情况下,只有一种方法可以实现无限循环 - 获取视图属性直到未设置.如果你写下(例如):

- (void)loadView {
   self.view = [[UIView alloc] initWithFrame:self.view.bounds];
}
Run Code Online (Sandbox Code Playgroud)

你会得到无限循环,但是

- (void)loadView {
   self.view = [[UIView alloc] initWithFrame:CGRectZero];
}
Run Code Online (Sandbox Code Playgroud)

工作正常.

因此,在未设置视图属性之前,您无法访问它.


pet*_*ine 4

由于您只是继承了超类(UIViewController)中正在实现的内容,因此如果您不调用超级方法,那么需要完成的实现就不会完成。

几乎所有 super 方法都会做一些关键的事情,并且继承超类实现的本地类必须一起重写它们(除非您通过参考文档了解 super 的所有功能,否则这永远不是一个好主意),或者只是将本地类实现添加到继承的超类实现。

总之,每当您继承一个类(在软件开发的大多数情况下)时,您都应该让超类执行其实现,除非可以安全地覆盖它们。

如果我是正确的,似乎 super loadView 实现了一些非常关键的东西来避免循环。

附加说明:但是,根据文档,您不应该调用 super 方法:http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html 可能的原因无限循环是由于未view正确实现属性引起的。