开发者

Utility methods in objective-c

Where should I place utility methods in objective-c?

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

开发者_JS百科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...


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜