Category为系统控件添加属性

158 阅读1分钟

我们都知道用category重写函数很方便,但是添加属性会各种警告. 我们可以利用runtime来添加属性.

头文件中:

@property (nonatomic,assign) BOOL lastImage;

m文件中:

#import <objc/runtime.h>

static void * lastImagekey=&lastImagekey;

然后在implementation中写入

- (void)setLastImage:(BOOL)lastImage{
    objc_setAssociatedObject(self, &lastImagekey, @(lastImage), OBJC_ASSOCIATION_ASSIGN);
}
- (BOOL)lastImage{
    return [objc_getAssociatedObject(self, lastImagekey) boolValue];
}

系统定义中有这么一段. 所以,就看你的@property写的是什么. 如果是assign 那就是OBJC_ASSOCIATION_ASSIGN .....

typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
                                            *   The association is made atomically. */
    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
                                            *   The association is made atomically. */
};