简体   繁体   English

loadview方法被多次调用

[英]loadview method is called several times

I create my views programmatically. 我以编程方式创建我的视图。 If I do not put loadView method, the app runs well. 如果我不放置loadView方法,则该应用程序运行良好。 However, When I add loadView method like this: 但是,当我添加如下的loadView方法时:

- (void)loadView
{
    NSLog(@"loadView is called");
}

I found this method was called many times! 我发现这种方法被调用了很多次! At last, the app crashed. 最后,该应用程序崩溃了。

I wonder why loadView method is called so many time. 我不知道为什么loadView方法被调用了这么多次。

Can anyone help? 有人可以帮忙吗? Thanks a lot! 非常感谢!

loadView is expected to, at some point, populate the view property of a view controller. 在某些时候,预计loadView会填充视图控制器的view属性。 The view property is lazily loaded (look at the call stack, you will see a method called something like _loadViewIfNeeded ). view属性是延迟加载的(查看调用堆栈,您将看到一个名为_loadViewIfNeeded的方法)。

If loadView doesn't create a view, then each time the .view property is accessed, the view controller will call loadView again, trying to lazily load the view. 如果loadView没有创建视图,则每次访问.view属性时,视图控制器都会再次调用loadView ,以尝试延迟加载视图。 At some point everything will go wrong because a view controller needs a view. 在某些时候,一切都会出错,因为视图控制器需要一个视图。 If you access self.view from within your custom loadView, you'll get an infinite loop. 如果您从您的自定义的loadView 访问self.view,你会得到一个无限循环。

From the documentation: 从文档中:

You can override this method in order to create your views manually. 您可以覆盖此方法,以便手动创建视图。 If you choose to do so, assign the root view of your view hierarchy to the view property . 如果选择这样做, 请将视图层次结构的根视图分配给view属性 The views you create should be unique instances and should not be shared with any other view controller object. 您创建的视图应该是唯一的实例,并且不应与任何其他视图控制器对象共享。 Your custom implementation of this method should not call super. 您对此方法的自定义实现不应调用super。

在加载视图中,您要调用[self loadView]而不是[super loadView]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM