Original link http://blog.csdn.net/meegomeego/article/details/18356169
The first kind : The method in Runtime.h
BOOL class_addProperty(Class cls,constchar*name,constobjc_property_attribute_t*attributes,unsignedint attributeCount)
#include <objc/runtime.h>#import<Foundation/Foundation.h>@interfaceSomeclass:nsobject {nsstring*_privatename;}@end@implementationSomeClass- (ID) init { self=[Super Init]; if(self) _privatename =@"Steve"; returnSelf ;}@endNSString*namegetter (IDSelf , SEL _cmd) {Ivar Ivar= Class_getinstancevariable ([SomeClassclass],"_privatename"); returnObject_getivar (self, Ivar);}voidNamesetter (IDSelf, SEL _cmd, NSString *newName) {Ivar Ivar= Class_getinstancevariable ([SomeClassclass],"_privatename"); IDOldname =Object_getivar (self, Ivar); if(Oldname! =newName) Object_setivar (self, Ivar, [newName Copy]);}intMainvoid{@autoreleasepool {objc_property_attribute_t type= {"T","@\ "nsstring\"" }; objc_property_attribute_t Ownership= {"C",""};//C = Copyobjc_property_attribute_t Backingivar = {"V","_privatename" }; objc_property_attribute_t attrs[]={type, ownership, Backingivar}; Class_addproperty ([SomeClassclass],"name", Attrs,3); Class_addmethod ([SomeClassclass], @selector (name), (IMP) Namegetter,"@@:"); Class_addmethod ([SomeClassclass], @selector (setName:), (IMP) Namesetter,"[Email protected]:@"); IDo = [SomeClassNew]; NSLog (@"%@", [o name]); [O SetName:@"Jobs"]; NSLog (@"%@", [o name]); }} output: Stevejobs
第二种:
- (ID) Valueforundefinedkey :( NSString *) Key
third: static const * const Objecttagkey; NSObject (examplecategorywithproperty) @dynamic Objecttag; -(id ) Objecttag { Objc_getassociatedobject (self, Objecttagkey);} -(void ) Setobjecttag: (id