实现多继承(protocol+消息转发)

创建类father、mom、son, son继承于father、mom

father

#import 

@protocol fatherDelegate 
-(void)driver;
@end

@interface father : NSObject

@end
#import "father.h"

@implementation father
-(void)driver
{
    NSLog(@"driver");
}
@end

mom

#import 

@protocol momDelegate 
-(void)cook;
@end
@interface mom : NSObject

@end
#import "mom.h"

@implementation mom
-(void)cook
{
    NSLog(@"cook");
}
@end

son

#import 
#import "father.h"
#import "mom.h"

@interface son : NSObject
@end
#import "son.h"
@interface son ()
@property(strong,nonatomic)father * f;
@property(strong,nonatomic)mom * m;
@end
@implementation son
-(instancetype)init
{
    if (self = [super init]) {
        self.f = [[father alloc]init];
        self.m = [[mom alloc]init];
    }
    return self;
}
- (id)forwardingTargetForSelector:(SEL)aSelector
{
    if ([self.f respondsToSelector:aSelector]) {
        return self.f;
    }
    else if ([self.m respondsToSelector:aSelector])
    {
        return self.m;
    }
    else
    {
        return self;
    }
}
//-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
//{
//    if ([self.f respondsToSelector:aSelector]) {
//        return [self.f methodSignatureForSelector:aSelector];
//    }
//    else if ([self.m respondsToSelector:aSelector])
//    {
//        return [self.m methodSignatureForSelector:aSelector];
//    }
//    else
//    {
//        return nil;
//    }
//}
//- (void)forwardInvocation:(NSInvocation *)anInvocation
//{
//    if ([self.f respondsToSelector:anInvocation.selector]) {
//        [anInvocation invokeWithTarget:self.f];
//    }
//    else if ([self.m respondsToSelector:anInvocation.selector])
//    {
//        [anInvocation invokeWithTarget:self.m];
//    }
//}
@end

在vc中使用son这个类

#import "ViewController.h"
#import "son.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    son * s = [[son alloc]init];
    [s driver];
}


@end

结果
2019-09-10 11:10:28.611041+0800 测试多继承[31932:1161314] driver

你可能感兴趣的:(实现多继承(protocol+消息转发))