initWithNibName VS viewDidLoad
我几个小时以来一直试图了解何时应该使用 viewDidload: 以及何时应该使用 initWithNibName: 来设置 viewController 的属性。
例如,我正在使用 TableViewController,并在 initWithNibName 中设置其所有属性(例如 backgroundColor、separateColor、工具栏项)。这是正确的做法吗?
如果有人能启发我。
谢谢
I've been trying to understand for hours when I should use the viewDidload: and when I should use initWithNibName: to set up the properties of my viewController.
For instance, I'm using a TableViewController and I'm setting all its properties (such as the backgroundColor, the separateColor, the toolbar items) in initWithNibName. It is the right way to do ?
If somebody could enlighten me.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该在
viewDidLoad
中设置您的属性。当控制器的视图加载到内存中时,系统会调用此方法。initWithNibName:
是您从 nib 文件创建控制器实例时调用的内容。也就是说,如果您在
initWithNibName:
中设置属性,而不是调用init
,您的控制器可能不会处于良好状态;因此,最好在viewDidLoad
中执行。You should set up your properties in the
viewDidLoad
. This method is called by the system when the controller's view is loaded into memory. TheinitWithNibName:
is something that you call when you create a controller instance from a nib file.That is to say, that if you set up your properties in the
initWithNibName:
and instead you callinit
, your controller might not be in a good state; thus, it's best to do inviewDidLoad
.您应该使用控制器的 viewDidLoad: 方法。引用 Apple 关于 initWithNib 的文档:
You should use viewDidLoad: method of your controller. To quote from Apple's documentation on initWithNib:
initWithNibName:在加载并实例化 NIB 时调用。
viewDidLoad:当视图实际呈现在屏幕上时调用。
是的 - 我相信在你的情况下,设置颜色等最好在 initWithNibName 中完成
initWithNibName: is called when the NIB is loaded and instantiated.
viewDidLoad: is called when your view is actually presented onscreen.
And yes - I believe that in your case, setting colors and such are best done in initWithNibName