Key Points of http://www.cnblogs.com/gugupluto/p/3159733.htmlObjective C Runtime Technology
Preface:
The runtime Technology of Objective C is very powerful. It can obtain and modify various class information at runtime, this section describes how to obtain the method list, attribute list, variable list, modification method, modifying attributes, adding methods, and adding attributes.
Directory:
(1) Use the class_replacemethod/class_addmethod function to dynamically Replace the function at runtime or add a new function.
(2) Reload forwardingtargetforselector and forward unhandled selector to other objects.
(3) resolveinstancemethod is reloaded to dynamically Add a selector when a selector cannot be processed.
(4) use class_copypropertylist and property_getname to obtain the attribute list of the class and the name of each attribute.
(5) Use class_copymethodlist to obtain the list of all methods of the class.
(6) Summary
(1) dynamically Replace the function at runtime: class_replacemethod
This function can be used to dynamically Replace the function implementation of a class at runtime. What is the purpose of this function? At the very least, you can achieve a hook effect similar to windows, that is, to intercept an instance function of the system class, and then add some of your own things, such as making a log or something.
Sample Code:
IMP orginIMP;NSString * MyUppercaseString(id SELF, SEL _cmd){ NSLog(@"begin uppercaseString"); NSString *str = orginIMP (SELF, _cmd);(3) NSLog(@"end uppercaseString"); return str;}-(void)testReplaceMethod{ Class strcls = [NSStringclass]; SEL oriUppercaseString = @selector(uppercaseString); orginIMP = [NSStringinstanceMethodForSelector:oriUppercaseString]; (1) IMP imp2 = class_replaceMethod(strcls,oriUppercaseString,(IMP)MyUppercaseString,NULL);(2) NSString *s = "hello world"; NSLog(@"%@",s];}
The execution result is:
Begin uppercasestring
End uppercasestring
Hello World
The role of this Code is
(1) obtain the function pointer of the uppercasestring function and store it in the orginimp variable.
(2) Replace the implementation of the uppercasestring function in the nsstring class with the custom myuppercasestring
(3) In myuppercasestring, the log code is executed first, and then the system implementation of the previously saved uppercasestring is called, so that you can add your own items before the system function is executed, when you call uppercasestring for nsstring, the log is printed.
Similar to class_replacemethod, class_addmethod can add a function for the class at runtime.
(2) When an object cannot accept a selector, the call to the selector is forwarded to another object.:-
(ID) forwardingtargetforselector :( SEL) aselector
Forwardingtargetforselector is a nsobject function. You can overload it in a derived class and forward unhandled selector to another object. Take uppercasestring as an example. If the User-Defined ca Class Object A does not have an instance function such as uppercasestring, directly execute [A performselector without calling respondselector: @ selector "uppercasestring"], crash will be executed. At this time, if the CA implements the forwardingtargetforselector function and returns an nsstring object, then the uppercasestring function is executed relative to the nsstring object, so no crash will be executed. Of course, the purpose of implementing this function is not only to make the program not as simple as crash, but also to use this function for message forwarding when implementing the modifier mode.
Sample Code:
1 @interface CA : NSObject 3 -(void)f; 4 5 @end 6 7 @implementation CA 8 9 - (id)forwardingTargetForSelector:(SEL)aSelector11 {13 if (aSelector == @selector(uppercaseString))15 {17 return@"hello world";19 }21 }
Test code:
CA *a = [CA new]; NSString * s = [a performSelector:@selector(uppercaseString)];NSLog(@"%@",s);
The output of the test code is Hello world.
PS: there is a problem here. The ca Class Object cannot receive @ selector (uppercasestring). If I use class_addmethod IN THE forwardingtargetforselector function to add an uppercasestring function to the CA class, and then return self, is it feasible? After testing, this will crash. At this time, the Ca class actually already has the uppercasestring function, but I don't know why it cannot be called. If we create a new CA Class Object and return it, yes.
(3) When an object cannot accept a selector, dynamically Add the required selector to the class to which the object belongs.:
+ (Bool) resolveinstancemethod :( SEL) Asel
This function is similar to forwardingtargetforselector and will be triggered when the object cannot accept a selector. The execution is slightly different. The former aims to give the customer a chance to add the required selector to the object, and the latter aims to allow the user to forward the selector to another object. In addition, the trigger time is not exactly the same. This function is a class function. When the program is started and the interface is not displayed, it will be called.
If the class cannot process a selector, if the class reloads the function and adds the corresponding selector using class_addmethod, and returns yes, then forwardingtargetforselector will not be called, if no corresponding selector is added to the function, no matter what is returned, the system will continue to call forwardingtargetforselector. If no object can accept this selector is returned in forwardingtargetforselector, the resolveinstancemethod will be triggered again. If selector is not added, the program reports an exception.
Sample Code 1: 1 @ implementation Ca 3 void dynamicmethodimp (ID self, Sel _ cmd) 5 {7 printf ("sel % s did not exist \ n ", sel_getname (_ cmd); 9} 10 11 + (bool) resolveinstancemethod :( SEL) asel13 {15 if (Asel = @ selector (t )) 17 {19 class_addmethod ([selfclass], Asel, (IMP) dynamicmethodimp, "V @:"); 21 return yes; 23} 25 return [superresolveinstancemethod: Asel]; 27} 28 29 @ end test code: Ca * CA = [Ca new] [Ca performselector: @ selector (t)];
Execution result
Sel T did not exist
Sample Code 2: @ implementation cavoid dynamicmethodimp (ID self, Sel _ cmd) {printf ("sel % s did not exist \ n", sel_getname (_ cmd ));} + (bool) resolveinstancemethod :( SEL) Asel {return yes;}-(ID) forwardingtargetforselector :( SEL) aselector {If (aselector = @ selector (uppercasestring )) {return @ "Hello World" ;}} test code: A = [[Ca alloc] init]; nslog (@ "% @", [a callback mselector: @ selector (uppercasestring)];
The output of the test code is Hello world.
For this test code, because a does not have the uppercasestring function, the resolveinstancemethod will be triggered. However, because this function does not add selector, it will be triggered if this function is not found during running.
The forwardingtargetforselector function returns an nsstring "Hello World" in the forwardingtargetforselector function. Therefore, the string executes the uppercasestring function and returns the uppercase Hello world.
Sample Code 3: @ implementation Ca + (bool) resolveinstancemethod :( SEL) Asel {return yes;}-(ID) forwardingtargetforselector :( SEL) aselector {return nil;} test code: 1 A = [[Ca alloc] init]; 2 nslog (@ "% @", [a callback mselector: @ selector (uppercasestring)];
The execution sequence of this Code is:
(1): The resolveinstancemethod is triggered when the program is just executed and the appdelegate has not been released,
(2) When the test code is executed, forwardingtargetforselector is called
(3) because forwardingtargetforselector returns nil, The uppercasestring selector cannot be found during the runtime. In this case, the resolveinstancemethod is triggered. Because the selector is not added, crash is triggered.
(4) use class_copypropertylist and property_getname to obtain the attribute list of the class and the name of each attribute.
u_int count; objc_property_t* properties= class_copyPropertyList([UIView class], &count); for (int i = 0; i < count ; i++) { const char* propertyName = property_getName(properties[i]); NSString *strName = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]; NSLog(@"%@",strName); }
The code above Retrieves all the attributes of uiview and prints the attribute name. The output result is:
skipsSubviewEnumeration viewTraversalMark viewDelegate monitorsSubtree backgroundColorSystemColorName gesturesEnabled deliversTouchesForGesturesToSuperview userInteractionEnabled tag layer _boundsWidthVariable _boundsHeightVariable _minXVariable _minYVariable _internalConstraints _dependentConstraints _constraintsExceptingSubviewAutoresizingConstraints _shouldArchiveUIAppearanceTags
(5) Use class_copymethodlist to obtain the list of all methods of the class.
The obtained data is a method array. The method data structure contains information such as the function name, parameter, and return value. The following code obtains the name as an example:
u_int count; Method* methods= class_copyMethodList([UIView class], &count); for (int i = 0; i < count ; i++) { SEL name = method_getName(methods[i]); NSString *strName = [NSString stringWithCString:sel_getName(name) encoding:NSUTF8StringEncoding]; NSLog(@"%@",strName); }
After the code is executed, the names of all functions in uiview are output. The specific results are omitted.
Other related functions:
1. sel method_getname (method M) Get sel2.imp method_getimplementation (method M) from method get imp function pointer 3. const char * method_gettypeencoding (method M) obtains type encoding information from Method 4. unsigned int method_getnumberofarguments (method M) to obtain the number of parameters 5. char * method_copyreturntype (method M) Get the return value type name 6.imp method_setimplementation (method M, IMP) to set a new implementation for this method
(6) Summary
In short, what can we do with the runtime technology?
You can perform many operations for various types (including System Classes) without inheriting or category at runtime, including:
Add function: class_addmethod to add the instance variable: class_addivar to add the attribute: @ dynamic tag or class_addmethod. Because the attribute is actually composed of the getter and setter functions, add protocol: class_addprotocol (to be honest, I really don't know how to add a protocol dynamically ,-_-!!)
Obtain the function list and information of each function (function pointer, function name, etc.): class_getclassmethod method_getname... get the attribute list and information of each attribute: class_copypropertylist property_getname get the information of the class itself, such as class name: class_getname class_getinstancesize get the Variable list and variable information: class_copyivarlist get the value of the Variable
Replace the instance with another class: object_setclass Replace the function with a function implementation: class_replacemethod directly modifies the value of the variable through the name in char * format, instead of using the variable