What does “@public” mean in Objective-C?
After reading a question on @private I understand how that works. However, since all variables default to @protected and you cannot really access a variable without defining an accessor, w开发者_StackOverflow社区hat exactly does @public do? When would you use it?
@public means that the ivar is accessible anywhere.
@private means that the ivar is accessible to instances of the class
@protected means the ivar is accessible to instances of the class and subclass.
To access a public ivar outside the class you use the standard C struct pointer operator -> e.g.
foo->instanceVarible = xyzzy;
When would you use it? In my case: never. I always define instance variables as @private (except IBOutlets) and use accessors to access them outside of the class.
When would you use it? When you need it to be public
. To access it from outside that class (without any extra accessors), that is. :)
@public
is a visibility modifier. It means that instance variables declared as @public
can be accessed by instances of any class. Public members can be accessed by subclasses or other classes. In contrast, private members cannot be accessed by subclasses or other classes.
This question is about coding practices.
If you are writing very strict code you would always use @private
for instance variables to ensure only the class functions could access them. In my opinion, this is only necessary in very specific instances, for example, class variables (where there is one variable for multiple instances of a class).
Most of the time @protected
is the most appropriate for normal instance variables as it allows subclasses to access them directly. It is much more natural and is consistent with the idea of extending a class. Depending on how you actually access them, Objective C might actually use the setter and getter functions of that class anyway. @protected
is desirable for efficient code and to make the code more readable.
The @public
is reserved for quick or dirty programming. Where it may be just quicker to access the instance member directly, or perhaps where you are interfacing with another programming language/library and you are writing some glue. I try to avoid it as it means code maintenance is more difficult.
Obviously you could just use @public
all the time - back to the good old days of C programming.
You can of course choose not define any accessors for a class variable because it is internal to the class or because you declare is as @public
but as Objective C makes it easy to prototype them with @property
and @synthesize
there does not seem much point. Internal class variables do not need setters/getters because any class method can access them directly.
精彩评论