tags:

views:

147

answers:

2

Where should I place utility methods in objective-c?

E.g. additional path handling utility methods which are called by multiple classes.

I have seen examples where they are placed in the main appdelegate file and are therefore available to all. This seems a bit weird to me though however...

+1  A: 

Yes, that is pretty weird (and bad practice).

Probably the commonest idiom is to use categories to extend existing system classes. In a few cases, where no system class is appropriate, some might create a utility class consisting mainly of class methods, or a singleton class with instance methods.

It depends on the methods and where they fit into the overall application structure (and always MVC behind things).

Paul Lynch
Singletons I would think are also overkill. I am looking for the equivalent to C++ utility classes with static methods or namespaces
Charlie
A good approach in one languages isn't necessarily the best approach in another.
Paul Lynch
The equivalent of C++ static methods are a class methods (methods starting with '+' instead of '-'). However I'd probably stick to just regular functions or maybe categories.
Tom Dalling
+3  A: 

You have a few options:

  • The simplest approach is to have a collection of C functions for common tasks (if you use a .m extension, you can use Objective-C objects within your C functions). From your code, for instance you would for instance call showAlertDialog().
  • You could have a "utility class" with a bunch of class methods that you import to every file. So for instance, you could call +[MyUtilities showAlertDialog]. This is the most direct equivalent to static utility classes in say Java, but it's a little clunky in Objective-C.
  • The other option, as Paul Lynch said, is to use categories to extend the common classes. The only problem with this is that it can lead to maintainability issues. It also only works to extend already-existing classes, and only when you don't need access to ivars. You could have a category for NSObject that would make the methods accessible from all your objects, but I would highly recommend against that (it could lead to severe maintainability headaches).

Personally, I use a mix of options 1 and 3. When I have functionality that's clearly tied to a particular existing class, I use categories. Otherwise, I use C functions.

eman