There are 3 modifiers: @private, @protected (default) and @public. Being accustomed to do so in C++ and other more sane languages, I always use @private for my fields. I barely (if ever)see that in SDK examples from Apple - they just rely on the default one.
One day I realized that Objective-C inheritance is rather fake feature: deriving an interface from another one doesn't mean all private fields are now available for redefinition. The compiler still sees them and disallows defining a new private field with the the same name, which goes orthogonal with classic encapsulation paradigm in OOD.
So I am a bit frustrated. Maybe I am expecting too much from the language because it's nothing more than a build up over standard C.
So do you use @private in your code? Why?
I guess it's a good idea to always use @private, but I've never bothered in the past because I generally use property accessors for almost all ivar access except in init and dealloc methods. So in practice, I rarely have a problem of accessing ivars by mistake.
Also, if you're targeting iOS 4+, you don't need to declare ivars for properties if you use @synthesize.
I should note that if you're writing library code that is meant to be subclassed by other developers, the use of @private would be more important.
I do out of habit, but it really doesn't matter unless you're shipping a binary framework others will link agianst, which I'm pretty sure you're not doing.
All @private does is restrict the visibility of the members of the object struct (accessed like obj->_ivar, rather than [obj getter] or obj.getter). It's a nice sanity check since it will error if you try to do it outside the class -- pretty much the only place to use direct structure access is when implementing NSCoding or NSCopying and those will still work -- but it doesn't really buy you much.
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