views:

63

answers:

2

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-

+2  A: 
dreamlax
+2  A: 

If you're creating a category, you have to give it some name. The name Private for 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 @implementation block. 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.

Chuck
@Chuck- Interesting- I had seen other examples with the nameless category, and that's exactly what had me confused. Thanks for pointing out the class extension vs category concept.
Yarin