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