Categories
Computing iphone Mac OS X

Private methods in Objective-C

Private methods in Objective-C are not something that is frequently discussed. Here’s how to make it happen.

Share

Coming from the Java world, I love, care and embrace all things private, including private methods. Objective-C supports the feature but it appears to me (based on very shallow Googling) that there is not too much familiarity (or use) with it. I looked in a book I recently acquired, Learn Objective-C for Java Developers (Learn Series). While not a book a perfect book, it does cover the how-to of private methods in Objective-C.  

The key to the approach is to leverage Objective-C categories. Categories are a mind-blowingly nifty in the fact that they allow you, among other things, to augment objects you did not create with your own methods. While there are other ways of 'hiding' private methods, most of them result in warnings in Xcode. So here goes…

Say you have an object called CoolWidget. You create the header file (CoolWidget.h)for it as usual, i.e.:

@interface CoolWidget:NSObject
{
    int publicVar;

    @private
    int somePrivateVar;
}

// public methods
-(void) doSomething:(BOOL)cool;

@end

To add private methods to it, you would create a category for the object in a separate header file (CoolWidget+Private.h):

@interface CoolWidget (Private)

// private methods
-(void) doSomethingPrivate:(BOOL)cooler;

@end

All that's left for you to do is to include the additional header file, CoolWidget+Private.h in your implementation file, CoolWidget.m (though categories are often/normally implemented in their own .m file).

Update:

As my friend Glenn Barnett points out in his tweet, there is no such think as private methods in Objective-C. Unlike C++ or Java, there is no real 'enforcement' of access to the methods. Privacy, overall, is purely by convention. 

Share

One reply on “Private methods in Objective-C”

Java privacy is only really “enforced” by the honor system, i.e. privacy is not enforced by the runtime, only by the compiler.
A good example is the fact that Spring can instantiate classes via private constructors. (apparently this is a feature, not a bug)

Leave a Reply

Your email address will not be published. Required fields are marked *

 

Share