iPhone 开发 - 以编程方式创建的视图中的 viewDidLoad 和 viewDidUnload ?
我在某处读到,在 UIViewController 中以编程方式创建的视图中,不使用 Interface Builder,不应使用 -viewDidLoad
和 -viewDidUnload
。这是对的吗?为什么?我应该在哪里释放我保留属性的子视图?或者我不应该使用它们的属性?
编辑:阅读我对 Rob Napier 的回答的评论。
I read somewhere that in a programmatically created view in a UIViewController, not using Interface Builder, -viewDidLoad
and -viewDidUnload
should not be used. Is this right? Why? Where would I release subviews that I have retaining properties of? Or should I just not use properties for them?
EDIT: Read my comments on Rob Napier's answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
-viewDidLoad
中创建子视图。如果您需要它们的 ivars,那么只需分配它们的值。通过将视图作为子视图添加到主视图来保留引用。然后,当您的视图被卸载时,您应该将 ivars 设置为 nil,因为自从您的视图被删除并释放后,该对象已被释放。
因此,在您的标头
和实现中,
如果您希望也可以不在
-viewDidLoad
中释放someSubview
,但您必须在-viewDidUnload
中释放它code> 和-dealloc
因为(如果我没记错的话)-viewDidUnload
在-dealloc
之前不会被调用。但如果您不保留someSubview
,则没有必要。Create your subviews in
-viewDidLoad
. If you need ivars for them then only assign their values. The reference is hold by adding the views as subviews to you main view.Then when your view is unloaded you should set your ivars to nil, because the object have been released since your view was removed and released.
So in your header
And in your implementation
If you wish you can also not release
someSubview
in-viewDidLoad
, but then you have to release it in-viewDidUnload
AND-dealloc
since (if I remember right)-viewDidUnload
isn't called before-dealloc
. But this isn't necessary if you don't retainsomeSubview
.这里奇怪的是,未从 NIB 文件加载的 UIViewController 不会收到有关其视图卸载的通知(因此不会调用其 viewDidUnload 方法),除非您提供 loadView 方法的基本实现,例如:
这仅发生在基本情况下UIViewController(例如 UITableViewController)不需要使用此解决方法进行修复。
所以罗布斯是对的。
the strange thing here is that an UIViewController not loaded from a NIB file is not notified about its view unloading (and so its viewDidUnload method is not called) unless you offer a base implementation of the loadView method, such as:
this only happens to base UIViewController, an UITableViewController for example don't need to be fixed with this workaroud.
So Robs is right.