Class Methods

Class methods are useful in general for two main purposes:

Factory methods
A factory method is a method that dispenses an instance of that class. For example, the UIFont class has a class method fontWithName:size:. You supply a name and a size, and the UIFont class hands you back a UIFont instance corresponding to a font with that name and size. A class method that vends a singleton instance, such as appears at the end of Chapter 1, is also a factory method.
Global utility methods
Classes are global (visible from all code, Chapter 13), so a class is a good place to put a utility method that anyone might need to call and that doesn’t require the overhead of an instance. For example, the UIFont class has a class method familyNames. It returns an array of strings (that is, an NSArray of NSString instances) consisting of the names of the font families installed on this device. Because this method has to do with fonts, the UIFont class is as good a place as any to put it.

Most methods that you write will be instance methods, but now and then you might write a class method. When you do, your purpose will probably be similar to those examples.

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.