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"]
}
@end
Thanks to Jonathan del Strother on the Cocoa-dev list for sharing this.
Tags: 3 Comments
3 responses so far ↓
I like this. It’s not even really a hack since there’s no language weirdness. It’s a logic hack.
I know this is late notice, but it occured to me there are memory issues here. When does the value get removed if the object that owns it (”self”) goes away? The category can’t implement dealloc.
That’s a good point. You would have to define your own dealloc-ish method in the category, and be sure it’s called before releasing the object. You might also be able to replace the static NSDictionary with an object that retains both the ivar and its parent, and periodically checks the parent’s retain count to see if it can be released along with its ivar.