After reading an article humbly named "The Code Commandments: Best Practices for Objective-C Coding" by Robert McNally a little less than two years ago, I adopted the practice of using properties for pretty much every data member of my Objective-C classes (the 3rd commandment as of may 2012). McNally lists these reasons for doing so (my emphasis):
- Properties enforce access restrictions (such as readonly)
- Properties enforce memory management policy (strong, weak)
- Properties provide the opportunity to transparently implement custom setters and getters.
- Properties with custom setters or getters can be used to enforce a thread-safety strategy.
- Having a single way to access instance variables increases code readability.
I put most of my properties in private categories, so number 1 and 4 are usually not issues I run in to. Arguments 3 and 5 are more 'soft', and with the right tools and other consistencies they could become non-issues. So finally, to me the most influential of these arguments was number 2, memory management. I've been doing this ever since.
@property (nonatomic, strong) id object; // Properties became my friends.
For my last few projects I've switched to using ARC, which made me doubt whether creating properties for pretty much anything is still a good idea or maybe a little superfluous. ARC takes care of memory managing Objective-C objects for me, which for most
strong members works fine if you just declare the ivars. The C-types you had to manually manage anyway, before and after ARC, and the
weak properties are mostly public ones.
Of course I still use properties for anything that needs access from outside of the class, but those are mostly only a handful of properties, while most data members are listed as ivars under the implementation header
As an experiment I've been doing this a bit more rigorously, and the move away from properties for everything has some nice positive side effects.
- Data member code requirements (
@synthesize) shrunk down to just the ivar declaration.
- Most of my
self.somethingreferences cleaned up to just
- It's easily distinguishable which data members are private (ivars) and which are public (properties).
- Lastly, it 'feels' more like this was the purpose Apple intended properties for, but that's subjective speculation.
On to the question: I'm slowly sliding towards
the dark side, using less and less properties in favor of implementation-ivars. Can you provide me with a bit of reasoning for why I should stick to using properties for everything, or confirm my current train of thoughts as to why I should use more ivars and less properties only where needed? The most persuasive answer for either side will receive my mark.
EDIT: McNally weighs in on Twitter, saying: "I think my main reason for sticking with properties is: one way to do everything, that does everything (including KVC/KVO.)"