Jul 29

Ok, this is easily my favorite feature of the Objective-C language thus far. That is Categories. Categories allows you to modify an existing class “in place”, without having to subclass. In many cases it doesn’t make sense to extend another class if you only wish to add functionality (but add no properties). Also, creating a Category does not require you to add to the inheritance chain which can be problematic if the class you are extending is not under your control.

For our example, I want to add functionality to NSString (a core foundation class). I’ll add a single Class Method that takes any string and presents it as if I’ve said it.

@interface NSString (MarksString)
+ (NSString *) markifyString:(NSString*)string;
@end

When writing the interface, you use the class you are extending (NSString) and define the category (MarksString). You can then add any additional interface elements here.

The implementation is just as expected:

@implementation NSString (MarkString)

   + (NSString *) markifyString:(NSString *) string {
      return [NSString stringWithFormat:@"Mark says \"%@\"", string];
   }
@end

To use this new category, all you have to do is #import the new category, which will add the functionality to NSString at run time.

NSString * original = @"Life is like a box of chocolate";
 NSLog([NSString markifyString:original]);

Displays:

2009-07-29 17:28:58.726 WhatATool[16449:10b] Mark says "Life is like a box of chocolate"

Comments are closed.

preload preload preload