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 异常
相关推荐
mascon28 分钟前
U3D打包IOS的自我总结
ios
名字不要太长 像我这样就好34 分钟前
【iOS】继承链
macos·ios·cocoa
karshey1 小时前
【IOS webview】IOS13不支持svelte 样式嵌套
ios
潜龙95272 小时前
第4.3节 iOS App生成追溯关系
macos·ios·cocoa
浮生带你学Java9 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)
java·开发语言·数据库·面试·职场和发展
游戏开发爱好者811 小时前
iOS App 电池消耗管理与优化 提升用户体验的完整指南
android·ios·小程序·https·uni-app·iphone·webview
然我13 小时前
数组的创建与遍历:从入门到精通,这些坑你踩过吗? 🧐
前端·javascript·面试
豆豆(设计前端)13 小时前
如何成为高级前端开发者:系统化成长路径。
前端·javascript·vue.js·面试·electron
一眼万年0414 小时前
Nginx Master-Worker 进程间的共享内存是怎么做到通用还高效的?
后端·nginx·面试
Cyan_RA915 小时前
写译 — 我靠!短进程优先调度算法究竟是怎么一回事?
面试·github·代码规范