Http://www.davidhamrick.com/2012/05/28/Adding-Properties-to-an-Objective-C-Category-Revisted.html
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 wocould have to manually add the setter and getter.
Static Char Kdhstylekey ; @ 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.
@ Interface Uiview (Dhstylemanager) @ Property ( Nonatomic , Copy ) Nsstring * Stylename ; @ End @ 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.
# Define add_dynamic_property (property_type, property_name, setter_name )\ @ Dynamic property_name ;\ Static char kproperty # property_name ;\ -(Property_type) property_name \ {\ Return (property_type) objc_getassociatedobject (self, & (kproperty # property_name ));\ }\ \ -(Void) setter_name property_type) property_name \ {\ Objc_setassociatedobject (self, & kproperty # property_name, property_name, objc_association_retain );\ }\