Monday, February 1, 2010

Objective-C Categories

Categories are a powerful tool for extending the functionality of existing classes in Objective-C. However, it's important to follow Apple's guidelines when using them to avoid any undefined behavior.

Categories allow you to extend the functionality of an existing class without subclassing. Before I get into an example, here are a few guidelines to follow when using categories. Apple recommends to not use categories to override methods in other classes, inherited classes, or other categories. Categories are not meant to add instance variables to classes either. If used in such contexts, the behavior of a program is undefined. Apple recommends using categories for adding functionality to large, existing classes and then grouping that functionality accordingly. Overriding existing Cocoa methods that are inherited from within the Cocoa hierarchy is a no-no as is extending methods that are already part of a category within the Cocoa hierarchy. Categories allow the addition of methods to existing classes while retaining the scope of class instance variables. So here's an example. Categories are quite simple to create and very powerful.

@interface UIViewController(myCategory)
- (void)messageName:(double)arga keywordA:(double)argb keywordB:(NSString *)argc;
#import "myController.h"

@implementation UIViewController(myCategory)
- (void)messageName:(double)arga keywordA:(double)argb keywordB:(NSString *)argc {
// process arguments
// do something with ivar
// ...
#import "myCategory.h"
@interface myController : UIViewController {

   someType ivar;

- (void) someMessage;
#import "myController.h"


- (void)someMessage {

   [self messageName];  // send message to self - i.e. call method defined by category