iOS:协议之多继承

2020-06-19  本文已影响0人  春暖花已开
#import "ViewController.h"

//协议
@protocol MZNameProtocol <NSObject>

@property (nonatomic, copy) NSString *name;
- (void)haveName;

@end


@protocol MZBreathProtocol <NSObject>

- (void)canBreath;

@end


//类
@interface MZCar : NSObject<MZNameProtocol>
@end

@implementation MZCar

- (void)haveName {
    NSLog(@"%@ have a name: %@", self.class, self.name);
}

@synthesize name;

@end


@interface MZDog : NSObject<MZNameProtocol, MZBreathProtocol>
@end

@implementation MZDog

- (void)haveName {
    NSLog(@"%@ have a name: %@", self.class, self.name);
}

- (void)canBreath {
    NSLog(@"%@ canBreath", self.class);
}

@synthesize name;

@end


@interface MZPerson : NSObject<MZNameProtocol, MZBreathProtocol>
@end

@implementation MZPerson

- (void)haveName {
    NSLog(@"%@ have a name: %@", self.class, self.name);
}

- (void)canBreath {
    NSLog(@"%@ can breath", self.class);
}

@synthesize name;

@end


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    MZCar *car = [[MZCar alloc] init];
    MZDog *dog = [[MZDog alloc] init];
    MZPerson *person = [[MZPerson alloc] init];
    
    car.name = @"car";
    dog.name = @"dog";
    person.name = @"person";
    
    //协议可以用作类型
    id<MZBreathProtocol> breathDog = [[MZDog alloc] init];
    [breathDog canBreath];
    
    [self linkTo:car];
    [self linkTo:dog];
    [self linkTo:person];
}

///协议可以作为参数
- (void)linkTo:(id<MZNameProtocol>)device {
    [device haveName];
}

@end
上一篇下一篇

猜你喜欢

热点阅读