Adding properties and methods to the IOS runtime

Source: Internet
Author: User

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   

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.