Private properties vs instance variables in ARC [d

2019-04-15 01:22发布

This question already has an answer here:

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!

2条回答
We Are One
2楼-- · 2019-04-15 01:41

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-04-15 01:42

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.

查看更多
登录 后发表回答