As I cannot create a synthesized property in a Category in Objective-C, I do not know how to optimize the following code:
@interface MyClass (Variant)
@prope
@lorean's method will work (note: answer is now deleted), but you'd only have a single storage slot. So if you wanted to use this on multiple instances and have each instance compute a distinct value, it wouldn't work.
Fortunately, the Objective-C runtime has this thing called Associated Objects that can do exactly what you're wanting:
#import
static void *MyClassResultKey;
@implementation MyClass
- (NSString *)test {
NSString *result = objc_getAssociatedObject(self, &MyClassResultKey);
if (result == nil) {
// do a lot of stuff
result = ...;
objc_setAssociatedObject(self, &MyClassResultKey, result, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return result;
}
@end