Search code examples
iosuiviewextend

Extend UIView and add property in iOS


I would like to add one property to UIView. I know I could subclass an UIView but as I want to add onelly one property I would like just to extend it.

I try like this :

@interface UIView (Util)
@property(nonatomic, assign) BOOL isShow;
@end

@implementation UIView (Util)
@dynamic isShow;

-(void)setIsShow:(BOOL)isShow{
    self.isShow = isShow;
}
@end

but it doesn't work. It throw an exception : Thread 1: EXC_BAD_ACCESS(code=2,address,...)


Solution

  • If you want to add a new property in a category you'll have to use objc_setAssociatedObject and objc_getAssociatedObject.

    Example:

    NSString *const IS_SHOW_KEY = @"IS_SHOW";
    
    @interface UIView (Util)
    @property (nonatomic) BOOL isShow;
    @end
    
    @implementation UIView (Util)
    
    - (void)setIsShow:(BOOL)isShow {
        NSNumber *val = @(isShow);
        objc_setAssociatedObject(self, (__bridge const void*)(IS_SHOW_KEY), val, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    - (BOOL)isShow {
        NSNumber *val = objc_getAssociatedObject(self, (__bridge const void*)IS_SHOW_KEY);
        return [val boolValue];
    }
    
    @end
    

    See the docs for the Runtime Reference here: https://developer.apple.com/library/ios/documentation/cocoa/reference/ObjCRuntimeRef/Reference/reference.html