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 异常
相关推荐
牛马11115 分钟前
Flutter iOS 权限配置完整指南(定位权限)
flutter·ios
A_QXBlms15 分钟前
多账号轮询架构 — 利用企销宝iPad协议突破单账号群发次数限制
ios·架构·ipad
java1234_小锋15 分钟前
Java高频面试题:Redis是单线程还是多线程?
java·redis·面试
明天有专业课16 分钟前
RAG-搞懂嵌入向量的生成
面试·aigc
哈里谢顿38 分钟前
服务器部署应用全流程指南
面试
MonkeyKing39 分钟前
iOS Runtime 深度解析
前端·面试
山栀shanzhi42 分钟前
深入C++之:一个类有几张虚函数表?
c++·面试
程序员库里1 小时前
第 3 章:Tiptap 与 React 集成
前端·javascript·面试
我叫黑大帅1 小时前
如何设计应用层 ACK 来补充 TCP 的不足?
后端·面试·go
HH思️️无邪1 小时前
Flutter + iOS 实战指南:教程视频 PiP + 退桌面(可复用模板)
flutter·ios