这是上一个问题的分支,这是不好的做法吗(使用属性来设置 iVar)?
// 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 中使用属性来访问 iVar 是不好的做法。
EDIT: Added retain
至版本 002
Gary.
是的,苹果劝阻在 init 或 dealloc 中使用访问器,因为它们除了设置实例变量之外还可能产生副作用。对于未初始化或已销毁的对象来说,这些显然是不受欢迎的。
Exact quote from the docs: "The only places you shouldn’t use accessor methods to set an instance variable are in init methods and dealloc."
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)