Methods of Class

Earlier, you might have been a little confused by this code:

[NSString stringWithUTF8String:"Even"]

With all the talk of sending messages to object instances, now you're not using one. Where the heck is that message going?

To begin answering that question, take a look at the definition in the NSString interface:

+ (id)stringWithUTF8String:(const char *)bytes;

Yep, it's another wacky character courtesy of Objective-C. This time it's a plus sign (+).

On The Methods Behind the Madness, you saw that methods were defined with a minus sign at the beginning. But those are just instance methods. Class methods are another kind.

With instance methods, you need a variable that references the object instance before you can send the message. Sometimes this is a limitation in your class design: You'd like to make a method available without an object instance. Class methods are Objective-C's solution to this problem. With these methods, you send messages directly to the class without needing an actual object.

These class methods are often used to create new object instances. The +stringWithUTF8String: method is just such a case; sending the message to the class lets it return a new object for you to use in your code.

Note

You may be familiar with using factory objects. That's exactly what sending a message to the class does. The +stringWithUTF8String: message acted as a factory for a new instance of NSString.

So what could make your AwesomeStringMaker class more awesome? A class method that ...

Get iPhone App Development: The Missing Manual now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.