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 异常
相关推荐
不简说4 小时前
JS 代码技巧 vol.4 — 10 个异步并发控制,Promise.all 这帮兄弟的踩坑实录
前端·javascript·面试
AIsoft_86884 小时前
iOS端录音转文字工具实测:自媒体创作者高效整理指南
ios·媒体
wear工程师7 小时前
Go 的 map 并发读写,面试里别上来就答「sync.Map」
面试·go
再吃一根胡萝卜8 小时前
别再只谈 Prompt 了,2026 年 AI 落地拼的是 Harness Engineering
人工智能·面试
浩哥学JavaAI8 小时前
2026年最新AI agent面试(09)_AI编程ClaudeCode
人工智能·面试·ai编程
时代的狂10 小时前
RabbitMQ 面试问答
分布式·面试·rabbitmq
Hyyy10 小时前
流式渲染的基础——SSE
前端·后端·面试
用户8524950718411 小时前
手把手教你打造专属 AI 技能(SKILL):从会议纪要秘书到 AI 日报主编
面试
KaifuZeng11 小时前
电路面试问题汇总一
单片机·嵌入式硬件·面试·电路
库奇噜啦呼11 小时前
【iOS】Core Data
ios