0

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,...)

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Marko Zadravec
  • 8,298
  • 10
  • 55
  • 97
  • possible duplicate of [Objective-C: Property in Category](http://stackoverflow.com/questions/8733104/objective-c-property-in-category) – Amar Dec 04 '13 at 10:49

2 Answers2

6

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

Ivan Genchev
  • 2,746
  • 14
  • 25
0

You should not add properties through category - you can only add methods. Read more here:

http://developer.apple.com/library/ios/#documentation/General/Conceptual/DevPedia-CocoaCore/Category.html

You can however achieve what you need by creating methods for setting / getting values you need.

@interface UIView (Util)
-(void)setIsShow:(BOOL)isShow;
@end

@implementation UIView (Util)
@dynamic isShow;

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

If you really need properties, than you need to subclass

Grzegorz Krukowski
  • 18,081
  • 5
  • 50
  • 71