Anonymous categories to the rescue

One of the things about Objective-C that seems a bit archaic to me is methods must be declared before they are called by other methods in the same code file. If you don’t, the compiler emits warnings. This is a remnant from classic C programming, which I have always found annoying. This limitation requires helper methods to be at the top of a code file, and the most important methods to be all the way down at the bottom. I prefer it the other way around.

Fortunately, Objective-C provides a solution for this issue in the form of anonymous categories. In case you are not familiar with categories yet, check out my post about them here. An anonymous category is one that has no name in between the parenthesis, such as:

@interface MyClassName ()

// method declarations go here…

@end

Here is an example of a situation that can benefit from this trick.  First look at my Foo class’s header file:

The implementation of that class is seen below:

Notice the compiler warning. If I moved the helpOut method above the doSomething method, the warning would go away.  But then my helper methods would be at the top of the file, which is what I want to avoid. So, to fix the problem, I declare my helper methods in an anonymous category just above the class to which it applies:

Now my helper methods can go below my primary methods, and all is well in the world.

About Josh Smith

Josh Smith is a musician at heart, and a software developer by obsession. He lives in Arizona, plays classical music on the piano, jazz on the guitar, and enjoys brutally long rides on his bicycle. He has a wonderful wife and thinks that, in general, life is good.
This entry was posted in Objective-C. Bookmark the permalink.

3 Responses to Anonymous categories to the rescue

  1. Mike Brown says:

    Interesting. Are you not allowed to declare the method in the header file and define it in the class file? Or is that essentially what you’re doing here?

    • Josh Smith says:

      In the header file you declare the methods that are the “public API,” so to speak, of the class. You wouldn’t want to put private helper methods in the @interface (i.e. header) because it would expose implementation details. So instead you put a category in the implementation file that contains the helper method declarations, which makes the ordering of those methods in the @implementation arbitrary.

Comments are closed.