Protected methods in Objective-C

Viewed 57561

What is the equivalent to protected methods in Objective-C? I want to define methods which only the derived classes may call/implement.

9 Answers

You can sort of do this with a category.

@interface SomeClass (Protected)
-(void)doMadProtectedThings;
@end

@implementation SomeClass (Protected)

- (void)doMadProtectedThings{
    NSLog(@"As long as the .h isn't imported into a class of completely different family, these methods will never be seen. You have to import this header into the subclasses of the super instance though.");
}

@end

The methods aren't hidden if you import the category in another class, but you just don't. Due to the dynamic nature of Objective-C it's actually impossible to completely hide a method regardless of a calling instance type.

The best way to go is probably the class continuation category as answered by @Brian Westphal but you'll have to redefine the method in this category for each subclassed instance.

I usually name protected method with internal prefix:

-(void) internalMethod;
Related