IPhone开发学习笔记:属性变量如何release?
为了释放对象拥有的实例变量,常用的方法是在dealloc中调用release,比如下面的代码:
@interface MyClass : NSObject {
NSString *name;
}
@end
@implementation MyClass
//something...
- (void)dealloc
{
[name release];
[super dealloc];
}
@end
如果这里的name是属性变量呢?在IPhone开发基础教程这本书里,你会经常在看到这样的代码:
@interface MyClass : NSObject {
NSString *name;
}
@property(retain) NSString *name;
@end
@implementation MyClass
@synthesize name;
- (void)dealloc
{
self.setName = nil;
[super dealloc];
}
@end
这里并没有直接访问变量本身,而是使用了编译器自动生成的setter。那问题就来了,咋的一赋值成nil,就能release了?想想看一般的setter的是怎么写的,看下面:
- (void) setName:(NSString *) value {
[value retain]; // calls [nil retain], which does nothing
[name release]; // releases the backing variable (ivar)
name = value; // sets the backing variable (ivar) to nil
}
ok,很方便的写法。但是不是说就没有问题呢?请参考下面的讨论,在KVC机制中是会有问题的。
http://stackoverflow.com/questions/192721/why-shouldnt-i-use-objective-c-2-0-accessors-in-init-dealloc
http://stackoverflow.com/questions/1283419/valid-use-of-accessors-in-init-and-dealloc-methods