From all code I've seen, almost always is used something like this for property scope definition:
Class extension
/*We declare the class extension*/
@interface MyClass ()
@property (nonatomic, retain) Type *aPrivateProperty;
- (void)aPrivateMethod;
@end
/*
We can use the main implementation block to implement our properties
and methods declared in the class extension.
*/
@implementation MyClass
/*Therefore we can use synthesize ;-)*/
@synthesize aPrivateProperty;
- (void)aPrivateMethod {
//Some code there
}
@end
But this is (from what I've seen) rarely used:
@interface MyClass : NSObject {
iVar *aProtectedIVar;
@public
iVar *aPublicIVar;
iVar *aSecondPublicIVar;
@protected
iVar *aSecondProtectedIVar;
@private
iVar *aPrivateIVAr;
}
@end
Why modifiers like @private, @protected and @public are not used so much in Objective-C if they are available?
Access modifiers for instance variables are rarely used because they expose more information about the structure of your object than you may wish to allow others to see. An exposure of a public variable is binding on all future implementations to have the same variable. Property, on the other hand, hides the variable, letting you change your mind later on, and compute result instead of storing it.
Property access is highly optimized in Objective-C, so there is virtually no run-time hit for exposing a property instead of a variable. Since you gain flexibility for free by switching to property, exposing variables with @public
is rarely used.
I was interested why class extension, (like from example above) is used more often than
@private
modifier
Because class extension lets you place private properties with your .m file, rather than your .h header file. Headers included from other .m files create compile-time dependencies, which are easily avoided by placing implementation details into class extensions.