Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utility methods in objective-c

Tags:

objective-c

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

like image 406
Charlie Avatar asked Apr 26 '10 21:04

Charlie


2 Answers

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.

like image 175
shosti Avatar answered Nov 15 '22 11:11

shosti


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

like image 31
Paul Lynch Avatar answered Nov 15 '22 12:11

Paul Lynch