I. Messaging mechanism 1. When invoking the DoSomething method directly in Viewdidload with the Performselector: @selector (dosomething), you will find that this method is not found. At this point, We can get this all at run time in Resolveinsantancemethod: (SEL) See method, in this method only need to judge, take this method to obtain, and use runtime's Class_addmethod method to bind the method and the response function to achieve the purpose of adding a method to a class. -(void) Viewdidload {
[Superviewdidload];
[Selfperformselector: @selector (dosomething)];} 1. The object is called RESOLVEINSTANCEMETHOD//2 after it has received a message that cannot be read. Then use Class_addmethod to associate the calling method name with the formulation function + (BOOL) Resolveinstancemethod: ( SEL) Sel {if (sel = = @selector (dosomething)) {
NSLog (@ "Add method here");
Class_addmethod ([Selfclass], SEL, (IMP) dynamicmethodimp, "[email protected]:");
Returnyes;
}
return [Superresolveinstancemethod:sel];} function void Dynamicmethodimp (idself,sel_cmd) {
NSLog (@ "dosomething SEL");} + (BOOL) Resolveclassmethod: (SEL) SEL {
NSLog (@ ">> Class resolving%@", Nsstringfromselector (SEL));
return [Superresolveclassmethod:sel];} Two. Message forwarding #import "ViewController.h"
@interfaceViewController ()
@end
@implementation Viewcontroller
-(void) Viewdidload {
[Superviewdidload];
[Selfperformselector: @selector (Messageviewmethod)];
}
/**
* @author Zhouyantong
*
* @brief In this method does not find or implement the corresponding method, then the message will be passed down, in the forwarding method to see whether the other interface has this method
*
*/
+ (BOOL) Resolveinstancemethod: (SEL) SEL {
return [Superresolveinstancemethod:sel];
}
-(ID) Forwardingtargetforselector: (SEL) Aselector {
Class class = Nsclassfromstring (@ "Messageviewcontroller");
Uiviewcontroller *VC = class.new;
if (Aselector = = nsselectorfromstring (@ "Messageviewmethod")) {
NSLog (@ "MESSAGEVC do this!");
return VC;
}
Returnnil;
}
-(void) didreceivememorywarning {
[Superdidreceivememorywarning];
Dispose of any resources the can be recreated.} #import "MessageViewController.h"
@interfaceMessageViewController ()
@end
@implementation Messageviewcontroller
-(void) Viewdidload {
}
-(void) Messageviewmethod {
NSLog (@ "This is receive method!");
}
@end
Runtime (message mechanism) + Runtime (message forwarding)