这是上一个问题的分支,这是不好的做法(使用属性设置 iVars)吗?
// Designated initializer 001
- (id)initWithName:(NSString *)newName andType:(NSString *)newType {
self = [super init];
if(self) {
[self setName:newName];
[self setType:newType];
}
return self;
}
或者我应该使用...
// Designated initializer 002
- (id)initWithName:(NSString *)newName andType:(NSString *)newType {
self = [super init];
if(self) {
name = [newName retain];
type = [newType retain];
}
return self;
}
我一直在使用版本 001,但被引导相信在 init 或 dealloc 中使用属性访问 iVars 是不好的做法。
编辑: 添加 retain
到版本 002
加里。
最佳答案
是的,苹果 discourages在 init 或 dealloc 中使用访问器,因为除了设置实例变量之外,它们还会产生副作用。这些在未初始化或已销毁的对象中显然是不受欢迎的。
文档中的确切引述:“唯一不应该使用访问器方法设置实例变量的地方是 init 方法和 dealloc。”
关于iphone - 使用属性访问 init 中的 iVars?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4091062/