iOS给类别添加属性

当向类别中添加自定义属性时会报instance variables may not be placed in categories错误,还好我们有了runtime,我们可以通过runtime的Associate为类别添加属性

@interface UIView (LFEaseBlankPageView)
{
NSString *test;/*报错instance variables may not be placed in categories */
}
@end

正确做法如下:


static char BlankPageViewKey;

- (void)setBlankPageView:(LFEaseBlankPageView *)blankPageView{
[self willChangeValueForKey:@"BlankPageViewKey"];
objc_setAssociatedObject(self, &BlankPageViewKey,
blankPageView,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self didChangeValueForKey:@"BlankPageViewKey"];
}

- (LFEaseBlankPageView *)blankPageView{
return objc_getAssociatedObject(self, &BlankPageViewKey);
}

你可能感兴趣的:(iOS给类别添加属性)