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…
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.