iPhone Development

Just another iPhone Blog

[self class] and static methods in Objective-C

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




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




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 response to “[self class] and static methods in Objective-C

  1. Russ Abraham November 5, 2011 at 7:30 pm

    I just stopped by your blog and thought I would say hello. I like your site design. Looking forward to reading more down the road.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: