Error when calling a static method using self from inside an instance of that class

A colleague recently came to me with a bug in his code, that he just couldn’t remove. He was attempting to call a static 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:

     return 1;

     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 doing 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 call self from the instance it won’t talk to the class method which is contained within a class object that itself has its own self!

To overcome this error you need to use: [className returnSomething], where className is the name of the class that the class method belongs to. The exact same as you would call that method from outside the instance.

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