消息转发机制

之前想了解runtime的先关知识,无意中发现了消息转发机制,就自己动手写了些。



如上图所示:在oc中调用方法时,本类及父类找不到此方法时,有如下步骤。
要重写一下方法。

第一步:尝试动态方法解析

Oc代码
  1. voiddynamicMethod(idself,SEL_cmd)
  2. {
  3. printf("SEL%sdidnotexist\n",sel_getName(_cmd));
  4. }
  5. +(BOOL)resolveInstanceMethod:(SEL)aSEL
  6. {
  7. class_addMethod([selfclass],aSEL,(IMP)dynamicMethod,"[email protected]:");
  8. returnYES;
  9. }

第二步:如果第一步返回NO,则进行【尝试快速消息转发】

Java代码
  1. -(id)forwardingTargetForSelector:(SEL)aSelector
  2. {
  3. Proxy*p=[[Proxyalloc]init];
  4. if([prespondsToSelector:aSelector])
  5. {
  6. returnp;
  7. }
  8. returnnil;
  9. }

第三步:如果第第二步返回nil,则进行【尝试标准消息转发】

Oc代码
  1. //检测此消息是否有效。
  2. -(NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector
  3. {
  4. return[ProxyinstanceMethodSignatureForSelector:aSelector];
  5. }
  6. -(void)forwardInvocation:(NSInvocation*)anInvocation
  7. {
  8. SELname=[anInvocationselector];
  9. NSLog(@">>forwardInvocationforselector%@",NSStringFromSelector(name));
  10. Proxy*proxy=[[Proxyalloc]init];
  11. if([proxyrespondsToSelector:name]){
  12. [anInvocationinvokeWithTarget:proxy];
  13. }
  14. else{
  15. [superforwardInvocation:anInvocation];
  16. }
  17. }

注:
调用函数:

Oc代码
  1. [fooperformSelector:@selector(MissMethod)];

Proxy类

Oc代码
  1. @implementationProxy
  2. -(void)MissMethod
  3. {
  4. NSLog(@">>MissMethod()calledinProxy.");
  5. }
  6. @end