Objective-C: Property / instance variable in category

前端 未结 6 1432
清酒与你
清酒与你 2020-11-22 16:56

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         


        
6条回答
  •  野性不改
    2020-11-22 17:29

    @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
    

提交回复
热议问题