xcode 何时使用 viewDidLoad 何时使用awakeFromNib

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14078708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:25:12  来源:igfitidea点击:

When to use viewDidLoad and when to use awakeFromNib

iosxcodeios6

提问by Doug Smith

I've gotten pretty comfortable using the viewDidLoad method to execute things I want done at the beginning of a view, but reading one of Apple's tutorials they set the data controller for the class in the awakeFromNib method and did nothing in the awakeFromNib. I swapped it and it seemingly worked identically in my app, but I'm not sure if it was better to have it in awakeFromNib or viewDidLoad.

我已经很习惯使用 viewDidLoad 方法在视图开始时执行我想要完成的事情,但是阅读 Apple 的一篇教程,他们在awakeFromNib 方法中为类设置了数据控制器,而在awakeFromNib 中什么也没做。我交换了它,它在我的应用程序中似乎工作相同,但我不确定将它放在awakeFromNib 或viewDidLoad 中是否更好。

When should I use either one?

我什么时候应该使用任何一种?

回答by onkar

awakeFromNibis called when the associated nib file with a class is loaded . Any class that can own a nib can use it. viewDidLoadis used only by view controllers. It is usually called when loading from nib as well but it can also be called by a view created in memory (very rare circumstance.). If you are using controllers, then I would suggest you to use viewDidLoad

awakeFromNib在加载具有类的关联 nib 文件时调用。任何可以拥有笔尖的类都可以使用它。viewDidLoad仅由视图控制器使用。它通常在从 nib 加载时也被调用,但它也可以被内存中创建的视图调用(非常罕见的情况。)。如果您使用的是控制器,那么我建议您使用viewDidLoad

For more Refer this Answer

有关更多信息,请参阅此答案

回答by Freeman

viewDidLoad is associated with the view controller. If you need to initialize another control unarchived from the nib (e.g. UITableViewCell prototype) you cannot overload viewDidLoad, you need to overload awakeFromNib.

viewDidLoad 与视图控制器相关联。如果您需要初始化另一个未从笔尖归档的控件(例如 UITableViewCell 原型),您不能重载 viewDidLoad,您需要重载awakeFromNib。