IOS Dynamic Add Attribute method

Source: Internet
Author: User

Write in front:

The dynamic addition of properties is not a wanton increase, it is required to write code. If a class does not have that property, it will be error-free at compile-time, resulting in a failure. The reason is also called dynamic add is generally because you can not rewrite a class, and the corresponding property to add it! Don't pull that much. Cut to the chase:

You first need to create a category to write to the appropriate Set/get method.

#import <UIKit/UIKit.h>@interface  UILabel (Associate)-(void) Setflashcolor: (Uicolor *) Flashcolor; -(Uicolor *) Getflashcolor; @end
uilabel+associate.h

The focus has come to realize:

#import "uilabel+associate.h"#import<objc/runtime.h>@implementationUILabel (Associate)Static CharFlashcolorkey;- (void) Setflashcolor: (Uicolor *) flashcolor{objc_setassociatedobject (self,&Flashcolorkey, Flashcolor, objc_association_retain_nonatomic);}-(Uicolor *) getflashcolor{returnObjc_getassociatedobject (Self, &flashcolorkey);}@end
UILABEL+ASSOCIATE.M

Call:

UILabel *lab = [[UILabel alloc] init];    [Lab Setflashcolor:[uicolor Redcolor];    NSLog (@ "%@", [Lab Getflashcolor]);
View Code

Thus: the addition of attributes using runtime is actually through "Objc_export void Objc_setassociatedobject (ID object, const void *key, id value, OBJC_ Associationpolicy policy) "to add the.

A pure C method, passing in an OC object, setting a value according to a key, this is the whole method.

Thinking:

。。。 Always feel that the implementation of the C function inside there is a large container ... (only for individuals who want to: )

Note: code from http://www.cnblogs.com/luoguoqiang1985/p/3551966.html

    

IOS Dynamic Add Attribute method

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.