Personal tools
You are here: Home News Objective-C Categories

Objective-C Categories

Objective-C Categories are a convenient way to extend existing classes

Categories are a nice feature in Objective-C. 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 categorie.   Apple recommends that you 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 your 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 you to add 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.

 

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

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

   someType ivar;
}

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

@implementation

- (void)someMessage {

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

@end

Document Actions