Add instance variables through a category

November 10, 2006

I saw this in Apple’s Cocoa-dev mailing list recently and thought it was clever. It’s a hack, and I don’t know of any situation off the top of my head where I’d use it, but if you need an instance variable in one of your categories ((For non-Cocoa programmers, a category is a powerful Objective-C tool that allows you to add new methods to an existing class. Although you can access existing instance variables you can’t add new ones, which is what this work-around accomplishes.)) I can’t see why it wouldn’t work.

static NSDictionary *ivarHolder = nil;

@implementation NSSomeClass (Additions)

-(NSString *)magicalValue
    if ( ivarHolder == nil )
        ivarHolder = [[NSDictionary alloc] init];

    NSDictionary *vars = [ivarHolder objectForKey:[NSNumber numberWithInt:self]];
    return [vars objectForKey:@"magicalValue"]


Thanks to Jonathan del Strother on the Cocoa-dev list for sharing this.

Marc Charbonneau is a mobile software engineer in Portland, OR. Want to reply to this article? Get in touch on Twitter @mbcharbonneau.