美文网首页
iOS:协议之多继承

iOS:协议之多继承

作者: 春暖花已开 | 来源:发表于2020-06-19 16:49 被阅读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

相关文章

网友评论

      本文标题:iOS:协议之多继承

      本文链接:https://www.haomeiwen.com/subject/qiqbxktx.html