Is it possible to declare a method as private in Objective-C?
A private method has a body in an interface means that we can't be declared as a normal abstract method as usually do in an interface.
Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.
If a method of a class is private, you cannot access it outside the current class, not even from the child classes of it. But, incase of an abstract method, you cannot use it from the same class, you need to override it from subclass and use.
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.
No, any object can send any message to any other object. You can, however, put the method in a category that's part of the class's implementation file. That way, you'll get a "Class may not implement this method" warning if you try to call it anywhere else. That's the normal way of making a method "private."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With