zoukankan      html  css  js  c++  java
  • OC消息转发

    1 重载 resolveInstanceMethod: 和 resolveClassMethod: 方法动态添加实例方法实现和类方法实现

    + (BOOL)resolveInstanceMethod:(SEL)sel {
    
    
        if (sel == @selector(setName:)) {
            
            class_addMethod([self class], sel, (IMP)setName, "v@:@");
            return YES;
        }else if (sel == @selector(name)){
            
            class_addMethod([self class], sel, (IMP)getName, "@@:");
            return YES;
        }
        
        return [super resolveInstanceMethod:sel];
    }

    2 消息转发机制执行前,Runtime 系统允许我们替换消息的接收者为其他对象。通过 - (id)forwardingTargetForSelector:(SEL)aSelector 方法。

    - (id)forwardingTargetForSelector:(SEL)aSelector
    {
        if(aSelector == @selector(mysteriousMethod:)){
            return alternateObject;
        }
        return [super forwardingTargetForSelector:aSelector];
    }

    3 完整消息转发阶段

    - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { 
      if(aSelector == @selector(testMethod)) 
      { 
        return [NSMethodSignature signatureWithObjCTypes:"v@:"]; 
      } 
      return nil; 
    } 
      
      
    -(void)forwardInvocation:(NSInvocation *)anInvocation 
    { 
      if (anInvocation.selector == @selector(testMethod)) 
      { 
        TestModelHelper1 *h1 = [[TestModelHelper1 alloc] init]; 
        TestModelHelper2 *h2 = [[TestModelHelper2 alloc] init]; 
        [anInvocation invokeWithTarget:h1]; 
        [anInvocation invokeWithTarget:h2]; 
      } 
    } 

    forwardingTargetForSelector仅支持一个对象的返回,也就是说消息只能被转发给一个对象

    forwardInvocation可以将消息同时转发给任意多个对象

  • 相关阅读:
    nginx下pagespeed使用详解
    letsencrypt证书-使用certbot申请wildcard证书
    letsencrypt证书-管理工具certbot
    tcpdump使用
    elasticsearch增删改查操作
    elasticsearch安装中文分词器
    dragstart drag dragend dragenter dragover dragleave drop
    js如何准确获取当前页面url网址信息
    /touch滑屏事件
    监听 手机back键和顶部的回退
  • 原文地址:https://www.cnblogs.com/jinlongyu123/p/10512531.html
Copyright © 2011-2022 走看看