<Span style = "font-family: Arial, Helvetica, sans-serif; Background-color: RGB (255,255,255);"> everyone must be familiar with the message forwarding mechanism in OC, now let's take a look: </span>
1. What is message forwarding?
@ Selector?
1. Sel
2 indicates the message (method) You want to send, which is a bit like a string and can also be transferred to each other .:Nsselectorfromstring ()/ Nsselectorfromstring ()
3. It can be understood as something similar to a function pointer-something that allows objective-C to dynamically call a method-it is a function pointer that object-C's dynamic post-binding technology can access through strings.
4 is actually the message response function-select a function address for the message response to your action
[Email protected] (function_name) is used to obtain the ID of a function.
The objc_msgxxx series functions are global functions.
Performselector is a nsobject member method, which has the same effect as Ms.
Ii. How to Implement Message forwarding?
1. implement method Signature
First, I am in zwrootviewcontroller. the H file defines a print method, but this method is not implemented. I want to process the messages received by the Controller instance by the zwobj class, in zwobj, I declare and implement the print method.
To forward a message, you must first construct a method signature. In zwrootviewcontroller, reload-(nsmethodsignature *) methodsignatureforselector (SEL) aselector method, this method returns a method signature for the zwrootviewcontroller instance to find the print method in zwobj (dynamic binding at runtime, one of the OC features)
-(Nsmethodsignature *) methodsignatureforselector :( SEL) aselector {nsmethodsignature * Signature = [Super methodsignatureforselector: aselector]; If (! Signature) {// determine whether the zwobj instance can respond to this selectorif ([zwobj instancesrespondtoselector: aselector]) {// obtain the method signature object signature of the zwobj selector = [zwobj failed: aselector] ;}} return signature ;}
2. Forward messages
-(Void) forwardinvocation :( nsinvocation *) Invocation {nslog (@ "invocation = [% @]", invocation); If ([zwobj instancesrespondtoselector: [invocation selector]) {// create the instance objzwobj * OBJ = [zwobj new] for handing over the message response permission; // activate the message in invocation, but the message responder is zwobj instead of the default self. [Invocation invokewithtarget: OBJ] ;}}
Source code download: http://download.csdn.net/detail/chuanfeng_liu/7894229
Technical Exchange Group: AI crazy, AI coding 209476515
Understanding of the message forwarding mechanism in OC and its practical application in the project