简体   繁体   English

释放Objective-C属性的最佳方法是什么?

[英]What's the best way to release objective-c properties?

I'm new to memory-management, and am reading different things about how to best release properties. 我是内存管理的新手,正在阅读有关如何最佳释放属性的不同内容。

If I have: 如果我有:
in .h: 在.h中:

@property(retain) NSString *myStr;

and in .m: 并在.m中:

@synthesize myStr = _iVarStr;

Should my dealloc have: 我的dealloc应该具有:

[_iVarStr release];  

or 要么

self.myStr = nil;   

or something else? 或者是其他东西?

Thanks! 谢谢!

Both self.myStr = nil and [myStr release] ultimately do the same thing. self.myStr = nil[myStr release]最终都做同样的事情。

Calling [myStr release] is obvious and just releases it. 调用[myStr release]很明显,只需释放它即可。

Meanwhile, the setter method for myStr looks roughly like this: 同时,myStr的setter方法大致如下:

- (void)setMyStr:(NSString *)newMyStr
{
    [newMyStr retain];
    [myStr release];
    myStr = newMyStr;
}

So when we do self.myStr = nil , we're first retaining a nil object, which does nothing. 因此,当我们执行self.myStr = nil ,我们首先保留一个nil对象,该对象什么也不做。 Then we release the old variable, which is what we want. 然后我们释放旧变量,这就是我们想要的。 Finally, we set the pointer to nil. 最后,我们将指针设置为nil。

What's the difference? 有什么不同? The latter sets the pointer to nil. 后者将指针设置为nil。 This is better because if we (accidentally) send a message to the released object, we crash if the pointer isn't nil (EXC_BAD_ACCESS). 这样做会更好,因为如果(偶然地)向已发布的对象发送消息,那么如果指针不是nil(EXC_BAD_ACCESS),我们就会崩溃。 Now honestly, since you're in -dealloc, the object is being destroyed anyways, so it wouldn't really matter what you use. 现在,说实话,由于您处于-dealloc状态,因此该对象无论如何都将被销毁,因此使用的内容并不重要。

Your dealloc should be this: 您的dealloc应该是这样的:

- (void)dealloc {
  [_iVarStr release];
  [super dealloc];
}

Although setting the property to nil is possible, I worry about unintended side effects or KVO actions triggered by the change that may not realize the object is currently being deallocated. 尽管可以将属性设置为nil,但我担心由更改触发的意外副作用或KVO操作可能无法意识到当前正在释放对象。

I recommend you use self.ivar=nil (the code ivar=nil previously I wrote was wrong) way in dealloc method. 我建议您在dealloc方法中使用self.ivar=nil (我之前编写的代码ivar=nil错误)。 Because, if the ivar's property change from retain to assign (or from assign to retain), you don't have to change your code. 因为,如果ivar的属性从“保留”更改为“赋值”(或从“赋值更改为保留”),则无需更改代码。

When a property is set to retain then 当属性设置为保留时

self.ivar = nil;

will properly manage the memory allocation. 将正确管理内存分配。 For other property types check the at the official documentation page. 对于其他属性类型,请查看官方文档页面上的。 It also has a bunch of sample code so you can understand what happens "under the hood" for all the options. 它还有许多示例代码,因此您可以了解所有选项“幕后”的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM