Objective C anonymous categoriesSep 14, 2010 · 3 minute read
I talked a while back about the use of Objective C categories as a way to extend existing classes without subclassing and also as a way to informally declare some private methods for a class. The anonymous category is an additional Objective C feature that provides an alternate way to declare private methods.
I should clarify what I mean by a private method since Objective C does not actually allow you to declare a method that cannot be called from outside the class. So when I talk about a private Objective C method I am referring to internal class methods that I do not intend to be called from outside the class. The declarations for these “private” methods will not appear in the public header file for the class and I generally place them at the top of the class implementation file as follows:
// MyClass.m @interface MyClass (privatemethods) - (void)someMethod; @end @implementation MyClass ....
If I was distributing this class as library with a public header file I could not prevent somebody from discovering the undocumented internal method name and then using it (you can always create a new category on the class to declare the undocumented method and then start calling it). Having got that disclaimer out of the way I will continue to refer to these methods as “private” methods for the rest of this post.
Note also that you are not forced to declare a private method in this way as long as the method definition occurs before it is used in the class file. I find it useful to do since I tend to put my private, internal, class methods at the end of the file so it avoids complaints from the compiler. Also I like to list those internal methods up front - something I suspect dates back to my C coding days when I would declare function prototypes at the top of the source code file in much the same way.
The Anonymous Category
Whilst declaring a category with a name such as “privatemethods” is fine I think the use of an anonymous category may be a better way to achieve the same thing. The anonymous category is similar to the named category we saw earlier except that, as the name suggests, it has no name.
// MyClass.m @interface MyClass () - (void)someMethod; @end @implementation MyClass ....
The main advantage of using an anonymous category over a named category is that the compiler will complain if you do not implement a method declared in the anonymous category. Also I find it cleaner to avoid having to name a category with what is essentially a meaningless name such as “privatemethods”.