I saw some code for an alternative way to store instance variables for a class (instead of just declaring them in the class’s header). I will show the code and then explain it:
@implementation NSObject(ExtraOutlet)
static CFDictionaryRef externalFooTable = NULL;
- (void)setFoo:(id)value {
LazyInit(externalFooTable, ...); // This just initializes if externalFooTable is nil.
if (value) {
CFDictionarySetValue(externalFooTable, self, value);
} else {
CFDictionaryRemoveValue(externalFooTable, self);
}
}
- (id)foo {
return externalFooTable ? CFDictionaryGetValue(externalFooTable, self) : nil;
}
@end
OK, so what is going on here? Well, let’s say you have a class, and you have a instance variable called foo (and subsequent KVC methods). If you don’t use foo a lot, or if there are very few instances of your class that will have foo be something other than nil, than you can store the value of foo per instance in a static hash table. The key to the hash table per instance is the instance’s address (self in ObjC).
Because of this static hash table, if you have 1,000,000 instances of your class, and you only have one instance that has foo be something other than nil, than you are saving 3.815 MB of RAM! And imagine doing this for a complicated program with lots of classes and instances, you could really have a major performance boost.You can use this method on your own classes, or as the example suggests, add additional instance variables to classes you didn’t write like NSObject, NSString, etc.
Thanks co-worker Jon for teaching me this one.
Kevin,
You truly are a nerd. But still, I love you my brother