Objective-C: Property / instance variable in category

categories, objective-c

Solution

@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 <objc/runtime.h>

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

Problem

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) @property (nonatomic, strong) NSString *test; @end @implementation MyClass (Variant) @dynamic test; - (NSString *)test { NSString *res; //do a lot of stuff return res; } @end ``` The test-method is called multiple times on runtime and I'm doing a lot of stuff to calculate the result. Normally using a synthesized property I store the value in a IVar _test the first time the method is called, and just returning this IVar next time. How can I optimized the above code?

Original source

Related problems