Even though Objective-C has support for private, protected and public instance variables, there is no notion of private methods. Every method is considered as public. However, there is an easy approach to make mock private methods by using categories.
//-------------------------------------------- // File: SomeClass.h //-------------------------------------------- @interface SomeClass + (void)publicClassMethod; - (void)publicInstanceMethod; @end
The interface definition would be the same; just declaring the public methods available (as shown above). However for the implementation of the class, an additional definition for the category would be required and the implementation for the private method will follow after the usual implementation for the class.
//--------------------------------------------
// File: SomeClass.m
//--------------------------------------------
@interface SomeClass (Private)
+ (void)hiddenClassMethod;
- (void)hiddenInstanceMethod;
@end
@implementation SomeClass
+ (void)publicClassMethod{
//This class method is public
};
- (void)publicInstanceMethod
//This instance method is public
}
@end
@implementation SomeClass (Private)
+ (void)hiddenClassMethod{
//This class method is private
}
- (void)hiddenInstanceMethod{
//This instance method is private
}
@end
To avoid writing a separate @implementation block for the private method, we can use "anonymous" categories. This is done and demonstrated below by omitting a name in the parentheses of the second @interface block.
//--------------------------------------------
// File: SomeClass.m
//--------------------------------------------
@interface SomeClass () //name is omitted for the category
+ (void)hiddenClassMethod;
- (void)hiddenInstanceMethod;
@end
@implementation SomeClass
+ (void)publicClassMethod{
//This class method is public
};
- (void)publicInstanceMethod
//This instance method is public
+ (void)hiddenClassMethod{
//This class method is private
}
- (void)hiddenInstanceMethod{
//This instance method is private
}
@end
Despite all these, one thing to be mindful of is that there are no true private methods in Objective-C. These mock private methods will still be available during run-time. The documented use of categories is to add methods to an existing class without requiring the actual source. It enables the functionality of the class to be extended without sub-classing.