Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: do you use @private visibility/access modifier in your code?

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?

like image 1000
Schultz9999 Avatar asked Dec 07 '25 09:12

Schultz9999


2 Answers

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.

like image 153
Daniel Dickison Avatar answered Dec 10 '25 00:12

Daniel Dickison


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.

like image 20
Colin Barrett Avatar answered Dec 10 '25 01:12

Colin Barrett