When to Use Class Methods in Objective C ?


A class in Objective-C can declare two types of methods: instance methods and class methods. An instance method is a method that is triggered when a message is sent to a particular instance of the class. In other words, before you call an instance method, you must first create an instance of the class. Class methods, by comparison, do not require you to create an instance. They are triggered when a message is sent to a class. In other languages, i.e. Java, class methods are called static methods.

One common use for class methods in Objective C or static methods in Java is to provide utility methods, i.e mathematical functions. A common example for static methods in Java are the static methods in java.lang Math. In Objective C you can often rely on pure C functions for utility methods, such as mathematical functions, so that you won't find many utility class methods in the frameworks, i.e. the fondation framework.

In Objective C you typically use class methods as (static) factory methods to create new instances of the class, which is an alternative to the object allocation and initialization procedure. For example NSString contains some very useful factory methods (like + (id)StringWithFormat:(NSString *)format) that return autoreleased NSString objects.

In his Book Effective Java (2nd Edition): A Programming Language Guide Joshua Bloch explained the advantages of of using factory (class/static) methods.Although Bloch's book was initially written for Java, most of his ideas are applicable to other object oriented languages.
One advantage of static factory methods is that, unlike constructors, they have names. A static factory with a well-chosen name is easier to use and the resulting client code easier to read. 
Most of the factory methods in the apple frameworks are good example for good naming convention as you can see in NSDate. You don't need much documentation to understand which objects are created by the following methods:

+ (id)dateWithTimeInterval:(NSTimeInterval)seconds sinceDate:(NSDate *)date
+ (id)dateWithTimeIntervalSince1970:(NSTimeInterval)seconds
+ (id)dateWithTimeIntervalSinceNow:(NSTimeInterval)seconds
A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.  
You can ensure that a certain class vends a singleton instance. The factory only creates an instance if the the instance doesn't exist. This is achieved with the with the following code snippnet:

static AccountManager *DefaultManager = nil;

+ (AccountManager *)defaultManager {
    if (!DefaultManager) DefaultManager = [[self allocWithZone:NULL] init];
    return DefaultManager;
}