Is it possible to declare a method as private in Objective-C?
objective-c
Solution
If you're working in Objective-C 2.0, the best way to create methods that are "hard" for others to call is to put them in a class extension. Assuming you have
@interface MyClass : NSObject {
}
- (id)aPublicMethod;
@end
in a `MyClass.h` file, you can add to your `MyClass.m` the following:
@interface MyClass () //note the empty category name
- (id)aPrivateMethod;
@end
@implementation MyClass
- (id)aPublicMethod {...}
- (id)aPrivateMethod {...} //extension method implemented in class implementation block
@end
The advanage of a class extension is that the "extension" methods are implemented in the original class body. Thus, you don't have to worry about which `@implementation` block a method implementation is in and the compiler will give a warning if the extension method is not implemented in the class' `@implementation`.
As others have pointed out, the Objective-C runtime will not enforce the privateness of your methods (and its not too hard to find out what those methods are using class dump, even without the source code), but the compiler will generate a warning if someone tries to call them. In general, the ObjC community takes a "I told you not to call this method [by putting it in a private class extension or category or just by documenting that the method is private] and you called it anyways. Whatever mess ensues is your fault. Don't be stupid." attitude to this issue.
Problem
Is it possible to declare a method as private in Objective-C?