Adding properties to an objective-C category-Revisted

Source: Internet
Author: User

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 );\  }\ 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.