Adding Properties to an Objective-C Category – Revisted

Posted by David Hamrick on


In my last post I wrote about adding properties to a category in objective-c. I have ended up using this feature quite a bit recently so I wrote a macro that will add the appropriate methods.

Before, when I wanted to add a category I would have to manually add the setter and getter.

@interface UIView (DHStyleManager)
@property (nonatomic, copy) NSString* styleName;
@end

@implementation UIView (DHStyleManager)
@dynamic styleName;
- (void)setStyleName:(NSString *)styleName
{
    objc_setAssociatedObject(self, &kDHStyleKey, styleName, OBJC_ASSOCIATION_COPY);
}

- (NSString*)styleName
{
    return objc_getAssociatedObject(self, &kDHStyleKey);
}

@end

Now, all I need to do is use the macro to create the getters and setters.

@implementation UIView (DHStyleManager)
ADD_DYNAMIC_PROPERTY(NSString*,styleName,setStyleName);

@end

All you need to do to use this macro is put this in a header file.



About.

David Hamrick is a partner at Hamrick Software, the makers of VueScan, the worlds most popular 3rd party scanner software.