[英]Should I programmatically add subviews in init or ViewDidLoad, and why?
I've been browsing some answers here and I get two different suggestions: 我一直在浏览一些答案,我得到两个不同的建议:
ViewDidLoad
. ViewDidLoad
添加。 Suggested in this answer Which one is the current best practice? 目前最好的做法是哪一个? The second answer seems to be older (2010), so I wonder if it's an old, no-longer-suggested, practice?
第二个答案似乎是较旧的(2010年),所以我想知道这是一个旧的,不再建议的做法吗?
No, never do such stuff in init. 不,永远不要在init中做这样的事情。
I viewDidLoad or even viewWillAppear, never in init because your view might not be there at the time, it kept happening to me when I was starting out that I was setting some string to a UILabel which wasn't there and made the app crash, but this worked in the simulator because it is so much faster than an actual device like iPhone 3. 我viewDidLoad甚至是viewWillAppear,从来没有在init中,因为你的视图当时可能不在那里,当我开始时我一直在向我发送一些字符串给UILabel而不是那里并使应用程序崩溃,但这在模拟器中起作用,因为它比iPhone 3这样的实际设备要快得多。
Same with resetting data and closing off delegates and such should not be set in dealloc. 与重置数据和关闭代理相同,不应在dealloc中设置。 Dealloc might not get called when you think it will.
你认为Dealloc可能不会被调用。 You should set such operations inside viewWillDissapear or viewWillUnload.
您应该在viewWillDissapear或viewWillUnload中设置此类操作。
For a non-XIB-based view controller, the correct place is in -loadView
. 对于非基于XIB的视图控制器,正确的位置在
-loadView
。 -loadView
is responsible for initializing a view controller's view
property, including any subviews. -loadView
负责初始化视图控制器的view
属性,包括任何子视图。 The system will call this method at the appropriate time. 系统将在适当的时间调用此方法。 You must assign something to the view controller's
view
property inside this method: 您必须在此方法中为视图控制器的
view
属性指定一些内容:
- (void)loadView
{
UIView *view = ...;
// create additional views here
self.view = view;
}
If you have a XIB-based view controller, the documentation says not to override -loadView
. 如果您有基于XIB的视图控制器,则文档说不要覆盖
-loadView
。 In this case, you should do additional view initialized work in -viewDidLoad
. 在这种情况下,您应该在
-viewDidLoad
执行其他视图初始化工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.