February 13, 2009

Private Methods in Objective-C

Most mainstream OO languages (C++, Java) support the notion of private, protected, and public class members. I've debated for years whether these protection attributes are really worthwhile, but it seems the designers of Objective-C felt protection for methods was not necessary. While you can add the various protection attributes to class and instance fields, you cannot do the same for methods.

There are several tricks you can employ, but I will present here the most straightforward and simplest approach. This trick uses the concept of class extensions, a bizarre facility that allows you to extend another class with replacement or additional methods. This technique is also sanctioned by the Apple Objective-C 2.0 Programming Language document (The Objective-C 2.0 Programming Language). To add a private method to your class, you extend your own class within your implementation (.m) file. This way, clients of your interface (.h) file do not see or know about your methods. For example:

// .h file to declare our class
@interface MyClass

// this is a public method
- (void) sayHi;

You'll notice in the header file, which is imported by users of your MyClass, has no mention of a private method. It is the implementation file where we put it:
// .m file to define our class
// but first let's extend our class with a private method
@interface MyClass ()

// this is a private method
- (void) tellSecret;

// now we implement everything
@implementation MyClass

// the public method
- (void) sayHi
  NSLog(@"Hello everyone!");

// the private method
- (void) tellSecret
  NSLog(@"Psst, ...");



  1. It is good that you don't have to prototype private methods in the header file. You can still call private methods publicly with only a warning. If you switch the order of the private methods, you'll get a warning. A common practice is to create a Category in the implementation file to forward prototype all private methods.

  2. Yes, with added hassle. One question I have concerning this technique is: can implementation code for the same class in another file access private methods declared and defined in a different file? My guess is no, so do we need a private .h file to declare all the privates?

    The hassle factor for private methods is really starting to pile up. I always question private methods in the first place.