简体   繁体   中英

Internal properties versus ivars

When I need a private object I currently use properties, like so:

// Class extension in .m file
@interface MyClass()
@property (strong, nonatomic) NSArray* myInternalArray;
@end

self.myInternalArray = something; 

Alternatively you can do this:

@implementation MyClass {

    NSArray* _myInternalArray;
}

_myInternalArray = something;

Without a custom setter or getter the two are equivalent. What is the best practice for internal variables? Are there any advantages of one method over the other?

While some may argue that the choice is a matter of preference, and they do have a point, there is a very good reason that most modern languages support properties and make them easier and easier to code.

The introduction of ARC does not significantly reduce the value of properties. It all comes down to this - in a property you have encapsulated the use of a variable. That encapsulation is invaluable when needed, and not much overhead when it is not.

For example (off of the top of my head) Suppose you discovered that you needed to validate the value before saving it. If you were using an iVar, you would have to ensure that anywhere that iVar was used, you had a call the validation code before you allowed it's value to be changed. With a property, you would only need to override setIVarName: and put the validation there. One could argue that one is just as easy as the other - and that may be true in many cases, but there is one handicap with the iVar here - you cannot ensure that future changes (by you or other coders) will insert the validation before the iVar is changed. Using a property here does have that assurance.

Personally, I use properties over iVars where ever possible.

I'd say that the advantage of properties is that you would use setters, and that setters can evolve independently of the code that call them. For instance, you could decide that setting a property would now trigger setNeedsLayout. By using properties from the start, you would have no need to refactor existing code.

This pattern fits very well in Cocoa/iOS APIs, where you don't have to ask system objects to do anything after having changed their properties: setters ensure internal and UI consistency right away.

The fact that properties are private should not make us implement them as second-class properties, what do you think?

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