Instance Variables for Objective C Categories

前端 未结 8 1892
终归单人心
终归单人心 2020-12-02 15:43

I have a situation where it seems like I need to add instance variables to a category, but I know from Apple\'s docs that I can\'t do that. So I\'m wondering what the best a

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 16:15

    This is best achieved using the built-in ObjC feature Associated Objects (aka Associated References), in the example below just change to your category and replace associatedObject with your variable name.

    NSObject+AssociatedObject.h

    @interface NSObject (AssociatedObject)
    @property (nonatomic, strong) id associatedObject;
    @end
    

    NSObject+AssociatedObject.m

    #import 
    
    @implementation NSObject (AssociatedObject)
    @dynamic associatedObject;
    
    - (void)setAssociatedObject:(id)object {
         objc_setAssociatedObject(self, @selector(associatedObject), object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    - (id)associatedObject {
        return objc_getAssociatedObject(self, @selector(associatedObject));
    }
    

    See here for the full tutorial:

    http://nshipster.com/associated-objects/

提交回复
热议问题