@property
声明存在一个属性(描述其接口),但没有指定该属性的实现。但属性需要将其内容存储在某处。默认情况下,编译器为该(和匹配的setter和getter)合成一个ivar。所以通常您可以忽略ivar的存在,并只使用点语法。
我遵循Apple的建议,并尽量避免直接使用ivars。但有时你想访问一个属性而不用调用它的getter。在我的代码最常见的例外是延迟初始化只读属性:
@interface MyObject : NSObject
@property (nonatomic, readonly) id someProperty ;
@end
@implementation MyObject
@synthesize someProperty = _someProperty ; // required; compiler will not auto-synthesize ivars for readonly properties
-(id)someProperty
{
if (!_someProperty)
{
_someProperty = ... create property here
}
return _someProperty ;
}
@end
而且,你可能不希望调用一个属性的getter你-dealloc
方法......例如,一个计时器属性。为了避免-dealloc
创建一个计时器,直接访问伊娃:
-(void)dealloc
{
[ _myTimer invalidate ] ; // don't use self.myTimer here, that would create a timer even though we're going away...
}
可能有更多的用例。对于大多数物业,你甚至不需要使用伊娃,只需使用<value> = self.property
和self.property = <new value>
。
编辑:
此外,将有用于经由信息分配访问属性(使用点存取语法或吸气剂)与直接访问的ivar一些额外的开销,但它会几乎在所有情况下都没有区别。