Objective C中,Category增加成员变量的2种方法

大家都知道,在OC中,如果是Category,是无法按照正常方法增加成员变量的。

有2种方法(实际是1种)

方法1:

static const void *PropArrayKey = &PropArrayKey;

- (NSMutableArray*)propArray {
    if(!objc_getAssociatedObject(self, PropArrayKey)) {
        objc_setAssociatedObject(self, PropArrayKey, [[NSMutableArray alloc] init], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return objc_getAssociatedObject(self, PropArrayKey);
}

方法2:

- (UIView *)myView {
    return [self associatedValueForKey:@selector(myView)];
}

- (void)setMyView:(UIView *)view {
    [self associateValue:view withKey:@selector(myView)];
}

 

Leave a Reply

Your email address will not be published.