什么时候发布IBOutlet?
我使用 Interface Builder 将 GUI 元素连接到视图控制器中的 IBOutlet,但不确定何时需要在 viewDidUnload 或 dealloc 中释放它们?或者两者都有?
谢谢!
I used Interface Builder to connect GUI elements to IBOutlet in view controller, but not sure when do I need to release them, in viewDidUnload or dealloc? Or both?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设它们是属性,您应该在 viewDidUnload 和 dealloc 中将它们设置为 nil,并确保使用 setter。因此,例如,
将保留属性设置为 nil 具有释放对象并将实例变量设置为 nil 的效果(因此即使在中间没有获得新对象,再次执行相同的操作也是安全的)。
当视图控制器的视图从内存中弹出时,将调用
viewDidUnload
,当发生内存警告并且视图控制器当前未使用其视图时,可能会发生这种情况。如果您为自己保留了一些子视图(隐式地,通过“保留”设置器或故意)并且不释放它们,它们将保留在内存中。您不希望他们这样做,因为您需要在收到内存警告时释放尽可能多的内存,并且如果系统范围内没有释放足够的内存,您或其他进程可能会被终止。因此,既要善待你的用户,又要成为一个好公民。无论您拥有保留还是分配属性,同样的建议都适用;如果它们被保留,那么将属性设置为 nil 将释放它们,如果它们刚刚被分配,那么将属性设置为 nil 将阻止您保留悬空指针。
Assuming they're properties, you should set them to
nil
in both viewDidUnload and dealloc, making sure to use the setter. So e.g.Setting a retain property to nil has the effect of releasing the object and setting the instance variable to nil (so it's safe to do the same thing again even without gaining a new object in between).
viewDidUnload
is called when your view controller's view has been ejected from memory, which can happen when a memory warning occurs and your view controller isn't currently using its view. If you've retained some subviews for yourself (implicitly, via a 'retain' setter or deliberately) and don't release them, they'll stay in memory. You don't want them to do that because you're required to free as much memory as possible upon receipt of a memory warning and you or other processes could be terminated if not enough memory is freed system wide. So it's both to be kind to your user and to be a good citizen.The same advice applies whether you've got retain or assign properties; if they're retained then setting the property to nil will release, if they're just assigned then setting the property to nil will prevent you from keeping a dangling pointer.
您应该在 dealloc 中释放 IBOutlets。
在 viewDidUnload 中,您应该释放在 viewDidLoad 中创建或保留的任何内容。
You should release IBOutlets in dealloc.
In viewDidUnload you should release anything you created or retained in viewDidLoad.