Calling a class method from an instance method

January 28th, 2011

A colleague recently came to me with a bug in his code, that he just couldn’t solve. He was attempting to call a static/class method from inside an instance method of his class using self, assuming that as self was an instance of the class it would have access to all the methods defined in that class.

Example code:

+ (int)returnSomething{
     return 1;
}

- (void)doSomething{
     int someValue = [self returnSomething];
}

The error occurred at line int someValue = [self returnSomething];, at first I couldn’t see much up with the code. However after some investigating it turned out that Objective-C does not have static methods as Java does but rather class methods, and these class methods are included in a class object which is separate from the instance object. Meaning that when you use self from the instance it only has access to instance methods and conversly when you use self in a class method it only has access to class methods.

To overcome this error you need to use: [ClassName returnSomething], where ClassName is the name of the class that the class method belongs to.

What do you think? Let me know by getting in touch on Twitter - @wibosco