Why Subclass When You Can Categorize

Recently, I’ve been trying to subclass NSString and add a method that I’ll be using in my application. After reading “Categories” by John Muchow, I decided to use categories. Instead of creating a new class, I would just add methods to an existing class.

Here is a simple example adding a newFunction to NSString. In your header file, you add “(CategoryName)” to the interface and declare the function you wanted to add.

@interface NSString (CategoryName)
- (NSString *)newFunction;
@end

You then implement newFunction in your implementation file.

@implementation NSString (CategoryName)
- (NSString *)newFunction {
// write your code here
}
@end

Now, if you import your header file in your code, you could just call “newFunction” just like any other function of NSString.

NSString *testString = [[NSString alloc] init];
[testString setString:@"String"];
[testString newFunction]; // this will call your function
[testString dealloc];

Of course, there will be cases when you need to subclass like when you want to add properties to a class, among others.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s