Creating New Classes

As you can see, categories can accomplish a lot and provide a great way to extend code that you didn't write. But they have one major limitation: You can't add instance variables in your category definition. And with the NSString class, how could you? The class interface tells you nothing about how the string is stored.

It's time to learn how to create new classes and to extend the Cocoa hierarchy. And to see how that's done, you're going to create a new class that lets you control the number of exclamation points, as in the phrase "THIS IS GOING TO BE AWESOME!!!!!!!"

The first thing to do is create an @interface for this new class:

@interface AwesomeStringMaker : NSObject
{
    NSNumber *exclamationCount;
    NSString *originalString;
}
- (NSNumber *)exclamationCount;
- (void)setExclamationCount:(NSNumber *)newExclamationCount;
- (NSString *)originalString;
- (void)setOriginalString:(NSString *)newOriginalString;

- (NSString *)awesomeString;
@end

This code looks similar to the class category on Implementation: The Brains Behind the Beauty. This time, the category name (in parentheses) is gone, and some new code is in curly braces: { }. A class's data is specified between these braces.

This example has two instance variables: a number that keeps track of the number of exclamation points and a string that you want to make awesome.

Note

You'll find that class data is referred to in many ways. Objective-C developers use the terms instance variable, ivar, and property interchangeably. ...

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.