问题描述
为iOS应用启用ARC,如果我希望某个类拥有私有值/对象,则应该更好地声明:
Having ARC enabled for an iOS app, if I want a class to have a private value/object, it should be better to declare this:
// .m file
@interface MyClass ()
@property (strong, nonatomic) NSString *name;
@end
还是这个?:
@implementation MyClass
{
NSString *name;
}
我应该考虑哪些内存管理?
What memory management considerations should I have?
谢谢!
推荐答案
您应该始终使用属性。我知道使用ARC使用ivar似乎等于使用属性,但它不是!!!!
属性有很多选项,其中一个非常重要的是原子/非原子。在堆栈上引用另一个:
You should always use properties. I know that with ARC use an ivar seems to equal to use a property, but it's not!!!!
Properties have a lot of options, one that is really important is atomic/nonatomic. Quoting another answer on stack:
另一个非常重要的是复制
如果你复制一个对象,你可以肯定(差不多)这个对象从你传入的时间开始没有变化。
The other really important is copy
if you copy an object you can be sure (almost) that this object didn't change from the time you passed in.
我喜欢属性,因为它们是方法,你可以覆盖他们。有时当我编写GUI元素时,我只想公开像text这样的属性。使用覆盖的设置器,您可以将文本直接传递给它应该显示的标签或文本字段。
Propeties为您带来很多好处,自从新版本的Xcode开始,ivar就会自动创建。
I love properties also because they are method and you can override them. Sometime when I write GUI elements I like just to expose just a property like "text". Whit an overriden setter you can pass the "text" directly to the label or textfield that it should show.
Propeties give you a lot benefits and since the newer version of Xcode the ivar is automatically created.
这篇关于ARC中的私有属性与实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!