Categories
Ever thought “Oh I wish Apple had included method X for class Y”, well that is what categories are for.
Categories are normally used for 2 things.
- Extending a class (using methods, not variables !!!)
- Logically separating a class into different functional areas
So lets look at something that is extremely popular at the moment ….. Twitter, and in paticular the 140 charachter limit.
Apple (for obvious reasons) don’t include Twitter related method calls on there string class NSString.
At the moment you would have to write everywhere in you code, something the resembles the following
NSString *twitterString = @"Objective-C rocks, I never want to look at Java again";
if ([[twitterString] length] < 141) {
// Post to twitter
}
Now this is good, but what if twitter changed their character limit, you would have to go an edit your code everywhere, where you used this check. So we are going add a method to the NSString class:
- (BOOL)isUnderTwitterCharachterLimit;
This will make are code look like this
NSString *twitterString = @"Objective-C rocks, I never want to look at Java again";
if ([twitterString isUnderTwitterCharachterLimit]) {
// Post to twitter
}
You now need an interface and implementation file, Im going to call them NSStringTwitterCategory.h and NSStringTwitterCategory.m
The interface file (NSStringTwitterCategory.h) is extremely small:
#import <Foundation/Foundation.h>
@interface NSString (Twitter)
- (BOOL)isUnderTwitterCharachterLimit;
@end
Instead of defining a new class in the format:
@interface NewClass: SuperClass {
}
You extend an existing class using the format:
@interface ClassYourExtending (CategoryName)
You can call the category whatever you want, but obviously you want to make it clear.
You then declare the methods like you always do.
The implementation file (NSStringTwitterCategory.m) is also not very complex:
#import "NSStringTwitterCategory.h"
@implementation NSString (Twitter)
- (BOOL)isUnderTwitterCharachterLimit {
if ([self length] < 141)
{
return YES;
} else {
return NO;
}
}
@end
Again you extend the class in the same way as you did in the header file:
@implementation NSString (Twitter)
And you simple define the method as you normally would, nothing strange or fancy. If you want to use this category you just need to import the header file where you want to use it.
This is obviously a very simple example, but I hope it shows you how to use categories in Objective-C.