Private properties vs instance variables in ARC [duplicate]

眉间皱痕 提交于 2020-01-01 19:38:10

问题


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

or this?:

@implementation MyClass
{
   NSString *name;
}

What memory management considerations should I have?

Thanks!


回答1:


You can use either approach. In the first case you are declaring a private property--which has some benefits. For instance you could expose that private interface elsewhere (eg: in a unit test) and access some of your class's internals. Plus as a property you have over control whether a pointer is weak or strong. In the second case you are declaring an ivar (instance variable) for your class, which can only be accessed from within your class's methods.




回答2:


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:

With "atomic", the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.

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.

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.



来源:https://stackoverflow.com/questions/17575119/private-properties-vs-instance-variables-in-arc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!