使用“保留”的对象泄漏
我有一个用保留属性定义的属性,我正在合成它:
@property (nonatomic, retain) UISwitch *mySwitch;
在我的 loadView 中我正在这样做:
self.mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 40, 20)];
最后在我的 dealloc 中我正在这样做:
self.mySwitch = nil;
我是否泄漏了这个对象(mySwitch),因为我使用了一个分配?我应该在分配框架时自动释放它吗?
请建议。
I have a property defined with retain attribute which I am synthesizing:
@property (nonatomic, retain) UISwitch *mySwitch;
And inside my loadView I am doing this:
self.mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 40, 20)];
And finally inside my dealloc I am doing this:
self.mySwitch = nil;
Am I leaking this object (mySwitch) as I have used one alloc? Should I autorelease it while assigning it frame?
Please suggest.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
该行:
实际上调用retain两次 - 一次用于
alloc
,并在对self.mySwitch
(这是您已经拥有的属性)的赋值中再次调用指定的应该保留
分配给它的任何值。)我被告知最好的修复是在线上添加对autorelease
的调用,使其:The line:
Actually calls retain twice- once for the
alloc
and again in the assignment toself.mySwitch
(which is a property you've specified shouldretain
any values assigned to it.) The fix I have been told is best is to add a call toautorelease
on the line, making it:是的,你正在泄漏。您正在使用
+alloc/-initWithFrame:
创建一个拥有的对象,然后将该拥有的对象分配给标记为retain
的属性。这将创建对该对象的第二个拥有的引用。此时,您泄漏了原始拥有的引用,这导致对象本身泄漏。这里正确的行为是在将对象分配给属性之前调用
-autorelease
。顺便说一句,不建议您访问
-dealloc
内部的属性。通常给出的两个原因是 1) 这将广播 KVO 通知,您不希望在-dealloc
内部发送该通知,2) 如果有人覆盖 setter(在此类或子类中)它可能无法正常工作。推荐的方法是简单地释放底层 ivar,因此您会看到类似以下内容:在其他地方将 nil 分配给该属性是完全安全的(并且推荐)。
Yes, you are leaking. You are creating an owned object with
+alloc/-initWithFrame:
, then assigning that owned object to a property markedretain
. This creates a second owned reference to the object. At this point, you leak your original owned reference, which causes the object itself to leak.The correct behavior here is to call
-autorelease
on the object before assigning it to the property.On a tangential note, it's not recommended that you access properties inside of
-dealloc
. The two reasons generally given for this are 1) this will broadcast KVO notifications, which you don't want inside of-dealloc
, and 2) if anyone overrides the setter (in this class or a subclass) it may not behave properly. The recommended approach is to simply release the underlying ivar, so you'd see something like the following instead:Assigning nil to the property is perfectly safe (and recommended) everywhere else.
作为自动释放的替代方案,如果您需要更严格的内存管理,这应该适合您:
稍后例如在 dealloc 中
As alternative to autorelease, if you need a tighter memory management this should work for you:
and later e.g. in dealloc
是的。你正在泄漏对象。请记住这里的一个简单规则:
如果您使用了
+alloc
,则始终必须有相应的-release
。Yes. You are leaking object. Remember one simple rule here:
if you used
+alloc
there is always must be corresponding-release
.