Using categories with private methods

Whilst writing yesterday about using categories with core data I forgot to mention the way I first started using categories. To be totally honest I was using them for a long time without even realising what they were or why they worked (never a good sign).

I came to Objective-C with experience in the usual range of procedural and object-oriented languages. I was used to the concept of public/private functions and interfaces and I quickly discovered that I could add methods to my class definition and call them via self:

[self someMethod];

Of course if you do this without defining the method in the class interface you get the familiar compiler warning message: ‘MyClass’ may not respond to ‘-someMethod’ To remove those warning methods you need some added magic in your class file:

// MyClass.m
@interface MyClass (privatemethods)
- (void)someMethod;
@end

@implementation MyClass
....

If you compare this with the examples from yesterday it is fairly obvious that this is actually just creating a category called privatemethods for MyClass. There is nothing magical about the name privatemethods of course, you could use any name you want.

The only difference with the examples from yesterday is that the interface declaration is included in the implementation file (before the implementation block) rather than in a separate header file named MyClass+privatemethods.h. Of course since these are intended to be private methods that makes perfect sense.

Never miss a post!

iOS Size Classes Cheat Sheet

Subscribe and get my free iOS Size Classes Cheat Sheet

Success! Now check your email to confirm your subscription and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
No time to watch WWDC videos?

Sign up to get my iOS posts direct to your inbox and I will send you a free PDF of my iOS Size Classes Cheat Sheet.

OK! Check your inbox (or spam folder) for an email to confirm your details and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
Archives Categories