Objective c 属性设置器中的垃圾收集和保留/释放

Objective c 属性设置器中的垃圾收集和保留/释放,objective-c,memory-management,properties,garbage-collection,Objective C,Memory Management,Properties,Garbage Collection,在阅读Objective-C属性时,我总是被告知要这样做setter(或者让属性机制来做setter): - (void)setMyProperty:(MyClass *)newValue { [newValue retain]; [ivInstanceVariable release]; ivInstanceVariable = newValue; } // or - (void)setMyProperty:(MyClass *)newValue { [ivInstan

在阅读Objective-C属性时,我总是被告知要这样做setter(或者让属性机制来做setter):

- (void)setMyProperty:(MyClass *)newValue
{
   [newValue retain];
   [ivInstanceVariable release];
   ivInstanceVariable = newValue;
}
// or
- (void)setMyProperty:(MyClass *)newValue
{
   [ivInstanceVariable autorelease];
   ivInstanceVariable = [newValue retain];
}
我不明白。我知道垃圾收集器的
retain
递增对象计数器,而
release
递减对象计数器,但更简单的方法是:

- (void)setMyProperty:(MyClass *)newValue
{
   ivInstanceVariable = newValue;
}

导致内存泄漏?谢谢。

调用set方法时,您不知道所传递对象的保留计数是多少。它可能是1,并且可能在调用set方法之后立即调用release

set方法负责通过调用retain来指示不应释放对象

至于调用release,当设置一个新值时,set方法应该对旧值调用release,以指示它不再需要它

最后,您应该按顺序对新值调用retain,对旧值调用release,因为可能会传递与已设置的值完全相同的值。

非原子retain”setter的经典模式是

- (void)setMyProperty:(MyClass *)newValue
{
if (ivInstanceVariable != newValue) {
 [ivInstanceVariable release];
 ivInstanceVariable = [newValue retain];
 }
}
if测试确保newValue是不同的,并且您没有在当前对象上调用release和retain。保留带来的额外开销不算太大,但使用复制则是另一回事

- (void)setMyProperty:(MyClass *)newValue
{
if (ivInstanceVariable != newValue) {
 [ivInstanceVariable release];
 ivInstanceVariable = [newValue copy];
 }
}

如果您是在启用垃圾收集的情况下构建应用程序,则
-retain
-release
都不是操作。@OP只要想想
retain
-
release
就可以了。仅获取对象的指针引用是不够的。