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 异常
相关推荐
摇滚侠1 小时前
面试实战 问题三十三 Spring 事务常用注解
数据库·spring·面试
while(1){yan}1 小时前
网络基础知识
java·网络·青少年编程·面试·电脑常识
测试人社区-千羽3 小时前
48小时攻克测试岗——闪电面试极速备战手册
人工智能·python·opencv·面试·职场和发展·单元测试·压力测试
风止何安啊5 小时前
拿捏 React 组件通讯:从父子到跨组件的「传功秘籍」
前端·react.js·面试
UCoding6 小时前
新能源技术面试 -- 给出一套mysql备份容灾方案
mysql·面试·主从
1024肥宅7 小时前
JavaScript性能与优化:手写实现关键优化技术
前端·javascript·面试
岁月向前8 小时前
Jenkins实现iOS自动化打包
ios
测试人社区-小明11 小时前
洞察金融科技测试面试:核心能力与趋势解析
人工智能·科技·面试·金融·机器人·自动化·github
星光不问赶路人12 小时前
new Array() 与 Array.from() 的差异与陷阱
javascript·面试
T___T12 小时前
Vue 3 做 todos , ref 能看懂,computed 终于也懂了
前端·javascript·面试