使用@property和@synthesize进行ivar隐式创建 [英] Using @property and @synthesize with ivar implicit creation
问题描述
好的,最近我得到了这个可能的坏习惯,用声明我的类属性@property
使用 @synthesize $创建getter和setter c $ c>并在我需要的任何地方使用它们作为
self.name
而不引用内部ivar(让 @synthesize
做它的工作)
Ok, so lately I got this presumable bad habit of declaring my class properties with @property
create getters and setters with @synthesize
and simply use them anywhere I need them as self.name
without having a reference to the inner ivar (let @synthesize
do its work)
现在,当然这不允许我访问内部的ivar(例如。 name _
)但是从我到目前为止编码的内容来看,我并不是真的需要它。对于只读属性,我不使用 @synthesize
,而是自己实现getter。
Now, of course this doesn't allow me to access the inner ivar (eg. name_
) but from what I've coded so far, I didn't really need it. For read-only properties I don't use @synthesize
but implement the getter myself.
一切似乎都很好,但不知何故,我感觉这是不对的,因为我已经查看了所有开源库,也宣告了ivar并在整个代码中使用它。 @property
+ @synthesize
并且没有ivar它绝对是懒惰的选择,但有什么缺点?有人可以给我一些建议吗?
Everything seems fine, but somehow I've got the feeling that this is not right because all the open source libraries I've had a look over, also declared the ivar and used it throughout the code. @property
+ @synthesize
and no ivar its definitely the lazy choice, but what are the drawbacks? Can someone give me some advice?
另外,我已经读过,作为一般建议,可以使用 self.propertyName
除了 dealloc
和 init
方法之外,你的类代码中的任何地方。但只要你确保对象是初始化:
Also, I've read that, as a general advice, it's OK to use self.propertyName
anywhere in your class code except the dealloc
and init
methods. But as long as you make sure the object is initialize:
-(id) init
{
if( (self=[super init] )) {
}
return self;
}
并在调用之前删除所有键值观察者[super dealloc]
一切都应该没问题。对吗?
and you remove all key-value observers before calling [super dealloc]
everything should be fine. Right?
推荐答案
以及 @synthesize
将创建内部ivar与属性相同的名称:
well the @synthesize
will create the inner ivar with the same name as the property:
@synthesize name;
- (void) dealloc {
[name release], name = nil;
[super dealloc]
}
或者给内部ivar另一个名字:
Or give the inner ivar an other name:
@synthesize name = _name;
- (void) dealloc {
[_name release], _name = nil;
[super dealloc]
}
我使用 self.name
在init中,但不在dealloc中,似乎工作得很好。
I use the self.name
in the init but not in the dealloc and seems to work great.
这篇关于使用@property和@synthesize进行ivar隐式创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!