Reputation: 335
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...
Upvotes: 5
Views: 3047
Reputation: 7422
You have a few options:
showAlertDialog()
.+[MyUtilities showAlertDialog]
. This is the most direct equivalent to static utility classes in say Java, but it's a little clunky in Objective-C. 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.
Upvotes: 6
Reputation: 19789
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).
Upvotes: 1