What kind of category methods do you use to make Cocoa programming easier?

categories, cocoa

Solution

I've really been loving Andy Matuschak's "KVO+Blocks" category on `NSObject`. (Yes, it adds some new classes internally as implementation details, but the end result is just a category on `NSObject`). It lets you provide a block to be executed when a KVO-conforming value changes rather than having to handle every KVO observation in the `observeValueForKeyPath:ofObject:change:context:` method.

Problem

I use a collection of category methods for Cocoa's built in classes to make my life easier. I'll post some examples, but I really want to see what other coders have come up with. What kind of handy category methods are you using? Example #1: ``` @implementation NSColor (MyCategories) + (NSColor *)colorWithCode:(long)code { return [NSColor colorWithCalibratedRed:((code & 0xFF000000) >> 24) / 255.0 green:((code & 0x00FF0000) >> 16) / 255.0 blue:((code & 0x0000FF00) >> 8) / 255.0 alpha:((code & 0x000000FF) ) / 255.0]; } @end // usage: NSColor * someColor = [NSColor colorWithCode:0xABCDEFFF]; ``` Example #2: ``` @implementation NSView (MyCategories) - (id)addNewSubViewOfType:(Class)viewType inFrame:(NSRect)frame { id newView = [[viewType alloc] initWithFrame:frame]; [self addSubview:newView]; return [newView autorelease]; } @end // usage: NSButton * myButton = [someView addNewSubviewOfType:[NSButton class] inFrame:someRect]; ```

Original source