I wrote an iOS application, it uses absolutely no variables, always uses the property. It was good?

advertisements

This question already has an answer here:

  • What is the difference between ivars and properties in Objective-C 2 answers

There are some benefit of using variables? Or it is OK to use property instead of variable?


It's not only OK to use properties instead of instance variables in many situations, it's often the preferred choice.

Until ARC came along, one important aspect of properties (or accessors generally) was that they simplified memory management by reducing the number of places where an object needed to be retained or released. That's not so important now that we have ARC, but it gives some background as to why some people choose properties over ivars almost everywhere. Other reasons to choose properties include key value observing, consistent syntax for accessing object state, a concise way to describe the semantics of an attribute, and future-proofing through encapsulation.

There's an idea that accessor functions break encapsulation by exposing the inner working of an object, and I think that's often a reason that people choose to use ivars instead of properties. I disagree, though: you can always hide your properties in a class extension so that they're only visible to the class, and in any case accessors allow you to change the implementation while still providing the same interface. In any case, if you don't want users of your class to rely on a given attribute, you can either make it an ivar or you can make it a property that's declared in a class extension.

Another argument for ivars is speed -- using a variable directly avoids calls to accessor method. IMO, the other benefits of properties vastly outweigh any speed advantage in general. If there's a specific case where an accessor call is a real problem, there are usually better ways to solve the problem than avoiding properties.