Best way to define private methods for a class in Objective-C

Yurii Soldak picture Yurii Soldak · Oct 5, 2008 · Viewed 178.6k times · Source

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:

  1. Xcode (and compiler?) does not check if you define all methods in private category in corresponding @implementation block
  2. 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.

Answer

Alex picture Alex · Mar 16, 2009

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.