[self class] and static methods in Objective-C

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Its been 5+ years of Objective-C programming and If I turn back and see, I have still a lot to learn.

I recently was working on a project, where a small design mistake look costlier. To overcome that, I had to override a set of static methods.

Let me give some insight into what happened before this.

 

I have seen many people use [self class] method in a static method, and I had always thought (my fault, i did not test it 🙁 ) that this would be always equal to the class name where the method is defined. But, I was wrong

 

So I had the following static method to create the Message model object

 

+(BBMessage*)newMessage

{

return [[[BBMessage alloc] init] autorelease];

}

+(BBMessage*)messageFromDictionary:(NSDictionary*)messageInfoDict

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

{

BBMessage *newMessage = [BBMessage newMessage];

….

}

 

This method was widely used to create the BBMessage object throughout the application. As it turned out be at the near end of the project, I had to add a subclass of BBMessage named BBHistoryMessage. However, the difference between BBHistoryMessage and BBMessage was a couple of  attributes in BBHistoryMessage, but their creation using method messageFromDictionary: remained same.

However, since it had [BBMessage newMessage] statement, the object created by messageFromDictionary: always created BBMessage instance rather than BBHistoryMessage’s instance

This is when I realized that replacing the appearances of BBMessage class name with [self class] as the [self class] would return the name of the class which invoked the method

 

For eg: if the BBHistoryMessage class  is used to invoke messageFromDictionary: then [self class] will be BBHistoryMessage class and hence newMessage would be creating BBHistoryMessage Class.

 

 

One thought on “[self class] and static methods in Objective-C

Leave a Reply

Your email address will not be published. Required fields are marked *