Using categories with private methodsMar 24, 2010 · 2 minute read
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:
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.