消息转发实现多继承
在OC 中,一个类只支持单继承,但是可以通过别的手段实现多继承。
利用消息转发实现多继承。
在OC 中,对象调用方法实际是在发消息,对象接收到一条消息的时候,消息函数随着对象的isa 指针到自己的方法列表中去寻找对应的方法,如果本类找不到,去父类中寻找,父类中找不到,继续沿着继承关系向上寻找,一直寻找到NSObject类别。如果到跟类没有找到,进行消息转发。
一下是实现步骤
创建三个类 StudentA StudentB StudentC, 让C 不继承 A 和 B ,但是同样的可以去调用A 和 B 的方法 ,其关键问题就是进行消息转发。
A
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface StudentA : NSObject
// 学生A 会游泳
- (void)swimming;
@end
NS_ASSUME_NONNULL_END
#import "StudentA.h"
@implementation StudentA
- (void)swimming
{
NSLog(@"i am A student, i can swimming");
}
@end
B
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface StudentB : NSObject
// 跑步
- (void)running;
@end
NS_ASSUME_NONNULL_END
#import "StudentB.h"
@implementation StudentB
- (void)running
{
NSLog(@"i am B student, i can running");
}
@end
C
#import <Foundation/Foundation.h>
#import "StudentA.h"
#import "StudentB.h"
NS_ASSUME_NONNULL_BEGIN
@interface StudentC : NSObject
/** */
@property (nonatomic,strong)StudentA *stuA;
@property (nonatomic,strong)StudentB *stuB;
@end
NS_ASSUME_NONNULL_END
#import "StudentC.h"
@implementation StudentC
- (StudentA *)stuA
{
if (!_stuA) {
_stuA = [[StudentA alloc]init];
}
return _stuA;
}
- (StudentB *)stuB
{
if (!_stuB) {
_stuB = [[StudentB alloc]init];
}
return _stuB;
}
// 实现此方法 进行消息转发
- (id)forwardingTargetForSelector:(SEL)aSelector{
if ([self.stuA respondsToSelector:aSelector]){
return self.stuA;
}else if ([self.stuB respondsToSelector:aSelector]){
return self.stuB;
}else{
return self;
}
}
@end
在VC 中打印对应的结果
StudentC *stu =[[StudentC alloc]init];
[stu performSelector:@selector(swimming)];
[stu performSelector:@selector(running)];
// 打印结果
// i am A student, i can swimming
// i am B student, i can running
备注:
当一个函数找不到的时候 ,OC 会有三种方式去进行补救
第一种就是 动态方法解析 resolveInstanceMethod
第二种就是 forwardingTargetForSelector,让别的对象去执行此方法
第三种就是 完整消息转发 methodSignatureForSelector
1万+

被折叠的 条评论
为什么被折叠?



