Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case for not using Properties in Objective-C

In the apple OS X 10.8 Core Library Documentation under Programming with Objective-C, it states,

"It's best practice to use a property on an object any time you need to keep track of a value or another object. If you do need to define your own instance variables without declaring a property, you can add them inside braces at the top of the class interface or implementation..."

So I'm curious, then, what are going to be the cases where you need to define instance variables without declaring properties? Aside from what apple says, could it really just be a personal preference thing?

Thanks!

like image 910
Ian Ray Avatar asked Dec 24 '12 00:12

Ian Ray


2 Answers

Some of it is definitely a matter of preference, but not everything: you are better off with a property for items with external visibility, and items that need different access control inside vs. outside your class. The issue has been much less pronounced since the introduction of ARC, because before it you may wanted to use properties for automated calls of retain and release. The significance of this aspect of properties has been reduced greatly to situations when you need to automatically copy the objects into your property.

like image 72
Sergey Kalinichenko Avatar answered Sep 21 '22 03:09

Sergey Kalinichenko


If you're using ARC and a recent runtime (recent enough to let you declare your ivars in your @implementation block), then instance variables are suddenly awesome again. Why? Because unlike @properties they're class-specific. No risk they'll accidentally be overridden by a subclass.

They're also faster in the simple case, since you don't call any methods to get or set them.

I personally also find it much cleaner. No more class extensions defining private @properties, and all that junk. Just ivars, nice and simple.

So the best advice, IMHO, is to use them by default. Only use @properties if you actually need their functionality, e.g.:

  • You need a way to access them from outside your class.
  • You want to allow subclasses to override them.
  • Your getter or setter is more than just a trivial assignment.

The latter two are all actually rarer than you might think. It's generally unwise to try to override properties in subclasses, just because it's a little unusual and there are some rough edges.

If you do find, later, that you need to upgrade an ivar to a @property, it's nice and easy - the only place it can be accessed is in your @implementation, so it's generally a simple search-and-replace to add "self." to its references (and maybe remove the leading underscore, if you name them that way). 'til then you needn't pay the cost and run the risks of using @properties.

like image 31
Wade Tregaskis Avatar answered Sep 21 '22 03:09

Wade Tregaskis