Best way to define private methods for a class in Objective-C
I just started programming Objective-C and, having a background in Java, wonder how people writing Objective-C programs deal with private methods.
I understand there may be several conventions and habits and think about this question as an aggregator of the best techniques people use dealing with private methods in Objective-C.
Please include an argument for your approach when posting it. Why is it good? Which drawbacks does it have (that you know of) and how you deal with them?
As for my findings so far.
It is possible to use categories [e.g. MyClass (Private)] defined in MyClass.m file to group private methods.
This approach has 2 issues:
- Xcode (and compiler?) does not check if you define all methods in private category in corresponding @implementation block
- You have to put @interface declaring your private category in the begin of MyClass.m file, otherwise Xcode complains with a message like "self may not respond to message "privateFoo".
The first issue can be worked around with empty category [e.g. MyClass ()].
The second one bothers me a lot. I'd like to see private methods implemented (and defined) near the end of the file; I do not know if that's possible.
Solution 1:
There isn't, as others have already said, such a thing as a private method in Objective-C. However, starting in Objective-C 2.0 (meaning Mac OS X Leopard, iPhone OS 2.0, and later) you can create a category with an empty name (i.e. @interface MyClass ()
) called Class Extension. What's unique about a class extension is that the method implementations must go in the same @implementation MyClass
as the public methods. So I structure my classes like this:
In the .h file:
@interface MyClass {
// My Instance Variables
}
- (void)myPublicMethod;
@end
And in the .m file:
@interface MyClass()
- (void)myPrivateMethod;
@end
@implementation MyClass
- (void)myPublicMethod {
// Implementation goes here
}
- (void)myPrivateMethod {
// Implementation goes here
}
@end
I think the greatest advantage of this approach is that it allows you to group your method implementations by functionality, not by the (sometimes arbitrary) public/private distinction.
Solution 2:
There isn't really a "private method" in Objective-C, if the runtime can work out which implementation to use it will do it. But that's not to say that there aren't methods which aren't part of the documented interface. For those methods I think that a category is fine. Rather than putting the @interface
at the top of the .m file like your point 2, I'd put it into its own .h file. A convention I follow (and have seen elsewhere, I think it's an Apple convention as Xcode now gives automatic support for it) is to name such a file after its class and category with a + separating them, so @interface GLObject (PrivateMethods)
can be found in GLObject+PrivateMethods.h
. The reason for providing the header file is so that you can import it in your unit test classes :-).
By the way, as far as implementing/defining methods near the end of the .m file is concerned, you can do that with a category by implementing the category at the bottom of the .m file:
@implementation GLObject(PrivateMethods)
- (void)secretFeature;
@end
or with a class extension (the thing you call an "empty category"), just define those methods last. Objective-C methods can be defined and used in any order in the implementation, so there's nothing to stop you putting the "private" methods at the end of the file.
Even with class extensions I will often create a separate header (GLObject+Extension.h
) so that I can use those methods if required, mimicking "friend" or "protected" visibility.
Since this answer was originally written, the clang compiler has started doing two passes for Objective-C methods. This means you can avoid declaring your "private" methods completely, and whether they're above or below the calling site they'll be found by the compiler.
Solution 3:
While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.
Solution 4:
Defining your private methods in the @implementation
block is ideal for most purposes. Clang will see these within the @implementation
, regardless of declaration order. There is no need to declare them in a class continuation (aka class extension) or named category.
In some cases, you will need to declare the method in the class continuation (e.g. if using the selector between the class continuation and the @implementation
).
static
functions are very good for particularly sensitive or speed critical private methods.
A convention for naming prefixes can help you avoid accidentally overriding private methods (I find the class name as a prefix safe).
Named categories (e.g. @interface MONObject (PrivateStuff)
) are not a particularly good idea because of potential naming collisions when loading. They're really only useful for friend or protected methods (which are very rarely a good choice). To ensure you are warned of incomplete category implementations, you should actually implement it:
@implementation MONObject (PrivateStuff)
...HERE...
@end
Here's a little annotated cheat sheet:
MONObject.h
@interface MONObject : NSObject
// public declaration required for clients' visibility/use.
@property (nonatomic, assign, readwrite) bool publicBool;
// public declaration required for clients' visibility/use.
- (void)publicMethod;
@end
MONObject.m
@interface MONObject ()
@property (nonatomic, assign, readwrite) bool privateBool;
// you can use a convention where the class name prefix is reserved
// for private methods this can reduce accidental overriding:
- (void)MONObject_privateMethod;
@end
// The potentially good thing about functions is that they are truly
// inaccessible; They may not be overridden, accidentally used,
// looked up via the objc runtime, and will often be eliminated from
// backtraces. Unlike methods, they can also be inlined. If unused
// (e.g. diagnostic omitted in release) or every use is inlined,
// they may be removed from the binary:
static void PrivateMethod(MONObject * pObject) {
pObject.privateBool = true;
}
@implementation MONObject
{
bool anIvar;
}
static void AnotherPrivateMethod(MONObject * pObject) {
if (0 == pObject) {
assert(0 && "invalid parameter");
return;
}
// if declared in the @implementation scope, you *could* access the
// private ivars directly (although you should rarely do this):
pObject->anIvar = true;
}
- (void)publicMethod
{
// declared below -- but clang can see its declaration in this
// translation:
[self privateMethod];
}
// no declaration required.
- (void)privateMethod
{
}
- (void)MONObject_privateMethod
{
}
@end
Another approach which may not be obvious: a C++ type can be both very fast and provide a much higher degree of control, while minimizing the number of exported and loaded objc methods.