#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
网友评论