In Apple's Programming with Objective-C the section on Encapsulating Data states that:
You Can Define Instance Variables without Properties
It’s best practice to use a property on an object any time you need to keep track of a value or another object.
In other words they are strongly recommending that you use private properties rather than instance variables for any private object state.
I am wondering why this might be the case? I understand that properties have features such as KVO, and attributes (strong, weak ...), but in many cases I do not need these features and an instance variable will work just fine.
Are there any good reasons why instance variables might not be considered best practice?
Instance variables are made private to force the users of those class to use methods to access them. In most cases there are plain getters and setters but other methods might be used as well.
In an ideal programming scenario, properties are declared public as they are exposed outside. Fields on the other hand are private as they should not be exposed because we do not have control over them when their value changes.
Q. Which is correct about an instance variable of type String? A. It defaults to an empty string.
Instance variables are declared in a class, but outside a method, constructor or any block. When space is allocated for an object in the heap, a slot for each instance variable value is created.
Even though right now your private variable might work as a plain variable, you may decide later that some of properties 'goodies' are useful:
If you only access your variables as properties, you don't add much overhead (except in tight cycles) and leave room for reaping any of those benefits described above.
Basically, properties are useful even if you don't ever plan on making them public.
Of course, there are places where using an instance variable is still 'more natural', for example if you reimplement Foundation classes in a class cluster (such as NSArray
), it's expected that your implementation is private and performant, so I don't use properties then.
Also, I don't think you should read too much into the advice. To me it reads more like "If you've only learned 5 minutes ago about properties and instance variables, let's start with using properties first".
People who are new to the language can go quite far without knowing what the instance variables are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With