何时使用实例变量和何时使用属性 [英] When to use instance variables and when to use properties
问题描述
当使用Objective-C属性时,您可以停止创建实例变量,或者显式的实例变量(而不是属性合成的变量)仍然用于属性不合适的用途?
p>不,你不能(在某种意义上)。你可以做的是停止声明它们,如果你有属性。如果你合成一个属性,并且你没有声明instvar,它将被声明为你,所以你正在创建一个实例变量,只是没有显式。
它们仍然服务于一个目的,其中属性不合适?
它以前是为创建属性的建议一切,因为有合成属性几乎所有的保留和发布为你。然而,使用ARC的原因使用属性来包装内存管理已经走了。现在的建议(对于ARC),我相信,使用属性来声明你的外部接口,但使用直接的实例变量,其中变量是对象的内部状态的一部分。
这是采用ARC的一个好理由:属性只是作为类的API的一部分恢复到它们的真正目的,不再需要使用它们作为一种隐藏内存管理工作的方法。
编辑
还有一件事:现在可以在 @implementation
,因此现在不需要在 @interface
中泄漏任何实现细节。即
@implementation MyClass
{
NSString * myString;
}
//方法定义
@end
我很确定它也能在类别中工作。 - 见下面的注释
When using Objective-C properties can you stop creating instance variables altogether or do explicit instance variables (not the ones synthesized by the properties) still serve a purpose where properties would be inappropriate?
can you stop creating instance variables altogether
No, you can't (in a sense). What you can do is stop declaring them if you have properties. If you synthesize a property and you haven't declared the instvar, it will get declared for you, so you are creating an instance variable, just not explicitly.
do they still serve a purpose where properties would be inappropriate?
It used to be the advice to create properties for everything because having synthesized properties does almost all of the retains and releases for you. However, with ARC that reason for using properties to wrap the memory management has gone away. The advice now (for ARC) is, I believe, use properties to declare your external interface, but use direct instance variables where the variable is part of the object's internal state.
That's a good reason to adopt ARC: properties revert to their true purpose only of being part of the class's API and it's no longer necessary to use them as a hacky way to hide memory management work.
Edit
One more thing: you can now declare instance variables in the @implementation
so there is now no need to leak any implementation details in the @interface
. i.e.
@implementation MyClass
{
NSString* myString;
}
// method definitions
@end
And I'm pretty sure it works in categories too. - see comment below
这篇关于何时使用实例变量和何时使用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!