Objective-C: Property / instance variable in category

前端 未结 6 1443
清酒与你
清酒与你 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:45

    .h-file

    @interface NSObject (LaserUnicorn)
    
    @property (nonatomic, strong) LaserUnicorn *laserUnicorn;
    
    @end
    

    .m-file

    #import 
    
    static void * LaserUnicornPropertyKey = &LaserUnicornPropertyKey;
    
    @implementation NSObject (LaserUnicorn)
    
    - (LaserUnicorn *)laserUnicorn {
        return objc_getAssociatedObject(self, LaserUnicornPropertyKey);
    }
    
    - (void)setLaserUnicorn:(LaserUnicorn *)unicorn {
        objc_setAssociatedObject(self, LaserUnicornPropertyKey, unicorn, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
    }
    
    @end
    

    Just like a normal property - accessible with dot-notation

    NSObject *myObject = [NSObject new];
    myObject.laserUnicorn = [LaserUnicorn new];
    NSLog(@"Laser unicorn: %@", myObject.laserUnicorn);
    

    Easier syntax

    Alternatively you could use @selector(nameOfGetter) instead of creating a static pointer key like so:

    - (LaserUnicorn *)laserUnicorn {
        return objc_getAssociatedObject(self, @selector(laserUnicorn));
    }
    
    - (void)setLaserUnicorn:(LaserUnicorn *)unicorn {
        objc_setAssociatedObject(self, @selector(laserUnicorn), unicorn, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
    }
    

    For more details see https://stackoverflow.com/a/16020927/202451

提交回复
热议问题