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 异常
相关推荐
2501_916008891 小时前
iOS 抓包工具有哪些?全面盘点主流工具与功能对比分析
android·ios·小程序·https·uni-app·iphone·webview
2501_915921431 小时前
iOS混淆工具实战 视频流媒体类 App 的版权与播放安全保护
android·ios·小程序·https·uni-app·iphone·webview
wifi歪f2 小时前
📦 qiankun微前端接入实战
前端·javascript·面试
绝无仅有2 小时前
未来教育行业的 Go 服务开发解决方案与实践
后端·面试·github
UrbanJazzerati4 小时前
掌握 xlwings 的 used_range:高效处理 Excel 数据区域
python·面试·excel
青鱼入云4 小时前
【面试场景题】spring应用启动时出现内存溢出怎么排查
spring·面试·职场和发展
007php0074 小时前
Go语言面试:传值与传引用的区别及选择指南
java·开发语言·后端·算法·面试·golang·xcode
小徐不徐说4 小时前
数据结构基础之队列:数组/链表
c语言·数据结构·算法·链表·面试
Spider_Man4 小时前
从 “不会迭代” 到 “面试加分”:JS 迭代器现场教学
前端·javascript·面试
2501_916008895 小时前
uni-app iOS 日志与崩溃分析全流程 多工具协作的实战指南
android·ios·小程序·https·uni-app·iphone·webview