May 27, 2014

Fast food objective-c (part 11) : Categories

Categories are one of the most useful features of Objective-C. Essentially, a category allows you to add methods to an existing class without subclassing it or needing to know any of the details of how it's implemented. 


This is particularly useful because you can add methods to built-in objects. If you want to add a method to all instances of NSString in your application, you just add a category. There's no need to get everything to use a custom subclass. 
For example, if I wanted to add a method to NSString to determine if the contents is a URL, it would look like this:
#import 
            
@interface NSString (Utilities)
- (BOOL) isURL;
@end
This is very similar to a class declaration. The differences are that there is no super class listed, and there's a name for the category in parenthesis. The name can be whatever you want, though it should communicate what the methods inside do. 
Here's the implementation. Keep in mind this is not a good implementation of URL detection. We're just trying to get the concept of categories across:
#import "NSString-Utilities.h"
            
@implementation NSString (Utilities)

- (BOOL) isURL
{
    if ( [self hasPrefix:@"http://"] )
        return YES;
    else
        return NO;
}

@end
Now you can use this method on any NSString. The following code will print "string1 is a URL" in the console:
NSString* string1 = @"http://pixar.com/";
NSString* string2 = @"Pixar";

if ( [string1 isURL] )
    NSLog (@"string1 is a URL");

if ( [string2 isURL] )
    NSLog (@"string2 is a URL");   
Unlike subclasses, categories can't add instance variables. You can, however, use categories to override existing methods in classes, but you should do so very carefully. 
Remember, when you make changes to a class using a category, it affects all instances of that class throughout the application.

No comments:

Post a Comment