The following is an example of how to create ‘private’ methods in Objective-C:
MyClass.m
#import "MyClass.h"
#import <stdio.h>
@implementation MyClass
-(void) publicMethod {
printf( "public method\n" );
}
@end
// private methods
@interface MyClass (Private)
-(void) privateMethod;
@end
@implementation MyClass (Private)
-(void) privateMethod {
printf( "private method\n" );
}
@end
Why does this example use the (Private) category name in the @interface MyClass (Private) and @implementation MyClass (Private) declarations? Aren’t interfaces declared in .m files automatically private? Do we need 2 different implementation blocks?
Is there a variation of this technique to create ‘protected’ methods?
(I’m new to objective-C. Am I missing the point of category names? Why do we need to use them in this instance?)
Thanks-
If you’re creating a category, you have to give it some name. The name
Privatefor the category doesn’t have any special meaning to the language.Also, in modern Objective-C, this would be a better case for a class extension, which is declared like a nameless category (
@interface MyClass ()) but the implementation goes in the main@implementationblock. This is a relatively recent addition, though. The secret-category method in your example is the more traditional way of accomplishing roughly the same thing.