iOS消息转发流程

当向Objc对象发送消息时,如果找到对象对应的方法,就会进入消息转发流程,给开发者提供一些最后的机会处理消息无法发送问题,以免出现程序崩溃。

  1. 回调对象的resolveInstanceMethod方法,在这个方法中,允许开发者在运行时为指定对象添加一个方法,然后返回YES。
objectivec 复制代码
 // 重写 resolveInstanceMethod: 尝试添加对象方法实现
+ (BOOL)resolveInstanceMethod:(SEL)sel{
    if (sel == @selector(way)) {
        class_addMethod([self class],sel,class_getMethodImplementation([self class], @selector(method)), "123");//使用class_addMethod动态添加方法method
    }
    return YES;
}
  1. 若用户未重写resolveInstanceMethod, 或者未能在重写方法中正确处理,则将会调用对象的forwardingtargetForSelector方法,该方法允许用户将消息转发到一个可以接收该消息的其他对象。
objectivec 复制代码
//尝试将消息转发到一个新对象
if (aSelector == @selector(way)) {
        Friends *friends = [[Friends alloc]init];
        return friends;//返回friends对象,让friends对象接受这个消息
    }
    return [super forwardingTargetForSelector:aSelector];
}
  1. 若上一步仍然未能正确处理, 对象的methodsignnatureForSelector & forwardInvocation方法将会被调用,允许用户在抛异常前进行最后的挽救。
objectivec 复制代码
//最后一次尝试对消息进行转发,可尝试多个转发对象
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
    if (aSelector == @selector(way)) {
        return [NSMethodSignature methodSignatureForSelector:@selector(way)];
    }
    return [super methodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation{
    SEL sel = anInvocation.selector;
    Friends *f = [[Friends alloc] init];
    if([f respondsToSelector:sel]) {   // 判断 Person 对象方法是否可以响应 sel
        [anInvocation invokeWithTarget:f];  // 若可以响应,则将消息转发给其他对象处理
    } else {
        [self doesNotRecognizeSelector:sel];  // 若仍然无法响应,则报错:找不到响应方法
    }
}
  1. 若消息仍未能正确处理,系统则会抛出unrecognized selector 异常
相关推荐
渣哥28 分钟前
多环境配置利器:@Profile 在 Spring 项目中的实战价值
javascript·后端·面试
飞哥的AI笔记40 分钟前
热题解析:什么是Few-shot Learning?为什么给几个例子模型就能学会?
面试
南北是北北1 小时前
Handler线程模型与内存
面试
汤姆Tom1 小时前
CSS 新特性与未来趋势
前端·css·面试
南北是北北1 小时前
Thread ↔ Looper ↔ MessageQueue ↔ Handler ↔ Message之间的关系
面试
南北是北北2 小时前
list并发与共享
面试
南北是北北2 小时前
泛型的三种型变类型:逆变,协变和不变
面试
游戏开发爱好者83 小时前
BShare HTTPS 集成与排查实战,从 SDK 接入到 iOS 真机调试(bshare https、签名、回调、抓包)
android·ios·小程序·https·uni-app·iphone·webview
ShooterJ3 小时前
Mysql小表驱动大表优化原理
数据库·后端·面试
小时前端3 小时前
🚀 面试必问的8道JavaScript异步难题:搞懂这些秒杀90%的候选人
javascript·面试