Instance Variables for Objective C Categories

前端 未结 8 1891
终归单人心
终归单人心 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:01

    It mentioned in many document's online that you can't create create new variable in category but I found a very simple way to achieve that. Here is the way that let declare new variable in category.

    In Your .h file

    @interface UIButton (Default)
    
       @property(nonatomic) UIColor *borderColor;
    
    @end  
    

    In your .m file

    #import 
    static char borderColorKey;
    
    @implementation UIButton (Default)
    
    - (UIColor *)borderColor
    {
        return objc_getAssociatedObject(self, &borderColorKey);
    }
    
    - (void)setBorderColor:(UIColor *)borderColor
    {
        objc_setAssociatedObject(self, &borderColorKey,
                                 borderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        self.layer.borderColor=borderColor.CGColor;
    }
    
    @end
    

    That's it now you have the new variable.

提交回复
热议问题