First, add a method to the class at run time
We first define a emptyclass, inherit NSObject, and have no own method, then define a function. Here, the Obj-c method is a C function that requires at least two parameters (Self,_cmd), and the function simply outputs a single word of hello. Next in the Addmethod method, we call Class_addmethod () to add a method to Emptyclass, which is defined by Class_addmethod ():
BOOL Class_addmethod (class cls, SEL name, IMP imp, const char *types)
Parameter description:
CLS: The class of the method being added.
Name: Can be understood as the method name, this seemingly casually named, for example, we call SayHello2.
IMP: A function that implements this method.
Types: A string that defines the return value type and parameter type of the function.
Then create an instance of Emptyclass, call SayHello2, run, output Hello, add method succeeds.
#if target_iphone_simulator#import <objc/objc-runtime.h> #else#import <objc/runtime.h> #import <objc/message.h> #endif @interface emptyclass:nsobject @end @implementation emptyclass @endvoidSayHello (ID Self, SEL _cmd) {NSLog(@"Hello");} - (void) Addmethod {Class_addmethod ([Emptyclass class],@selector(SayHello2), (IMP) SayHello,"[Email protected]:");//Test MethodEmptyclass *instance = [[Emptyclass alloc] init]; [Instance SayHello2]; [Instance release];}
Second, why not rewrite the original class method
The main reasons are as follows:
Many of cocoaframework are implemented in category, and after rewriting, there is only one method that will be executed at runtime and which will be executed as undefined.
For example, one method of overriding NSString is base64encodedstring, while other cocoaframework may use category to implement this method, which results in runtime Which method to execute is undefined.
In addition, there is a place to note that is the name of the category method.
The usual way is to add a prefix, such as
-(void)WC_setUpCustomButton;
Because, now the name does not conflict, iOS version is updated, the SDK is also updated, that is, to try to ensure that the name of future methods do not conflict.
Three, the joint storage implementation mode and the underlying principle analysis
The biggest benefit of dynamic languages is flexibility, and for objective-c, the ability to dynamically add methods and instance variables to classes at run time is the envy of many other languages. Now let's talk about adding the technology used for the instance variable to the class: federated storage.
I. How federated storage is implemented
The following code implements the addition of the color property for the Duck class:
Duck+associative.h file
#import "Duck.h" @interface Duck (associative) @property (nonatomicNSString *color; @end
DUCK+ASSOCIATIVE.M file
#import "duck+associative.h" #import <objc/runtime.h> @implementation Duck (associative)Static CharColorKey =NULL; - (NSString*) Color {returnObjc_getassociatedobject ( Self, &colorkey); } - (void) SetColor: (NSString*) Acolor {objc_setassociatedobject ( Self, &colorkey, Acolor, Objc_association_retain); }
Invocation Examples:
Duck *smallDuck = [[Duck alloc] init]; smallDuck.color = @"red color"; NSLog(@"duck color:%@",smallDuck.color); [smallDuck release];
Output Result:
2013-07-18 19:09:26.578ObjcRunTime[429:403]duckcolor:redcolor
At this point, we have successfully added a color attribute to the Duck class.
Iv. advantages and disadvantages of federated storage
1. Advantages
The greatest advantage of federated storage is that it can be implemented in a flexible way to add attributes to a class.
2. Disadvantages
Inefficient, the real instance variables can be accessed using a single machine instruction, but there are several function calls to access the values stored in the mapping table, and the efficiency issue needs to be noted.
In fact, many cocoa classes, such as Nsattributedstring, Nsfilemanager, Nsnotification, and nsprocessinfo, are widely used in federated storage.
Reference Links:
- iOS adds a method to a class at run time
- Objective-c adding attributes and principle parsing through federated storage for classes
- IOS-How to add a property to 1 classes
- ADD variables to a existing class in Objective-c
- Faking instance variables in Objective-c categories with associative References
iOS class Add method, attribute learning notes