iPhone 开发 - 释放自动释放的对象
如果我释放自动释放的对象会发生什么? 我想释放它的一个自动释放的 UIButton,创建 UIButton 的唯一方法是使用便捷方法 buttonWithType: 。 它会像普通对象一样从内存中释放吗? 或者我应该让自动释放池来处理它? 如果可以的话,我一开始就不会让它自动发布。
谢谢!!
What happens if I release an autoreleased object? Its an autoreleased UIButton I want to release and the only way to create a UIButton is to use the convinience method buttonWithType:. Will it be released from memory like a normal object? Or should I just let the autoreleasepool take care of it? I wouldn't have made it autoreleased in the first place if I could.
Thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只能释放您拥有的对象。 +buttonWithType: 不返回拥有的对象,因此您不能释放它。
查看 Cocoa 对象所有权规则。
为什么你要在这里避免自动释放对象? 假设您正在创建该按钮,因为您正在使用该按钮并将其插入视图层次结构中,因此没有真正的理由加速包含该按钮的自动释放池的耗尽。
You must only release an object which you own. +buttonWithType: does not return an owned object, so you must not release it.
Review the Cocoa Object Ownership Rules.
Why are you trying to avoid an autoreleased object here? Presumably you are creating the button because you are using the button and inserting it into a view hierarchy, so there is no real reason to accelerate the draining of the autorelease pool which contains the button.
你应该让自动释放池来处理它。 将按钮添加到父视图后,该视图将保留它,并且自动释放句柄将由自动释放池处理。
最简单的思考方式是从所有权角度考虑——您并不“拥有”通过便捷方法获得的引用,因此您无需费心释放它,除非您也保留它。
You should just let the autorelease pool take care of it. Once you add your button to a parent view, that view will retain it, and the autoreleased handle will get taken care of by the autorelease pool.
The easiest way to think of it is in terms of ownership—you don't "own" the reference you got via a convenience method, so you don't need to bother releasing it unless you retain it as well.