简体   繁体   中英

ARC: what's the difference between a member variable and property?

I have an NSArray object that is used throughout my UIViewController. I can either declare it as an ivar or as a property. Is there any advantage to either approach (considering I'm using ARC)?

Option 1:

@interface MyViewController {
    NSArray *_myArray;
}
@end

Option 2:

@interface MyViewController
    @property (strong, nonatomic) NSArray *myArray;
@end

Properties and ivars are conceptually quite different.

A property represents a logical component of your code. It may, but need not, be backed by an ivar. It could be dynamically generated calculated at run-time (like a view's -frame ), etc.

An ivar is an actual allocated block of memory holding some data.

If you use properties (correctly), you get nice features like KVC/KVO compliance out of the box. For this and other reasons it is often thought to be good practice, especially with the modern run-time, to declare all public interfaces in the form of properties, and internally back them with ivars (frequently using @synthesize ) if appropriate.

Personally, I prefer to use properties for private data as well, both to make it easy to make public later if I want (just move the declaration to the header!) and to make it easy to provide custom implementations of properties (and setters/mutators) instead of relying on a simple ivar.

Since you mention ARC, I haven't used it much (yet) but I don't think it should make much of a difference as long as you declare your property correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM