Saturday, December 04, 2010

Best Way to Implement Private Methods in Objective-C

Since the iPhone SDK came out, I've been using the following syntax in my Objective-C implementation file (the .m) to implement private methods:

@interface ClassName (Private) - (void)privateMethod; @end

@implementation ClassName - (void)privateMethod { //keep this private }
@end

This style just creates a Category for your class that's not in the header, so other classes can't read it. Turns out there was an even better way introduced in the Objective-C 2.0 spec using Extensions, which are like anonymous categories, but the improvement is the implementation must exist in the main implementation block for the class. Here's the example re-written:

@interface ClassName () - (void)privateMethod; @end

@implementation ClassName - (void)privateMethod { //keep this private } @end

Not much has changed, instead of decorating your category with a name, (Private), you just put empty parenthesis, ().

Once I switched over the iTimeZone code base, realized I was carrying some dead weight method declarations, so win!

Here's Apple's documentation.

Update
Check out bbum's comment for additional syntactical sweetness to make private/public properties with property redeclaration.