协议是用于定义类或多个类应该遵守的规范
案例:
#import <Foundation/Foundation.h>
@protocol Output
@required//必须实现
-(void)output;
@optional//可选择实现
-(void)addData:(NSString*)msg;
@end
#import <Foundation/Foundation.h>
@protocol Productable
-(NSDate*)getProductableTime;
@end
#import <Foundation/Foundation.h>
#import "Output.h"
#import "Productable.h"
@protocol Printable <Output,Productable>
-(NSString*)printColor;
@end
#import <Foundation/Foundation.h>
#import "Printable.h"
@interface Printer : NSObject<Printable>
@end
#import "Printer.h"
@implementation Printer
-(void)addData:(NSString*)msg {
NSLog(@"添加数据:%@",msg);
}
- (void)output {
NSLog(@"输出数据");
}
- (NSDate *)getProductableTime {
return [NSDate date];
}
- (NSString *)printColor {
return @"返回了内容";
}
@end
#import <Foundation/Foundation.h>
#import "Printer.h"
#import "Printable.h"
#import "Productable.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Printer* printer = [[Printer alloc]init];
[printer addData:@"呵呵呵"];
//通过协议来定义变量
NSObject<Productable>* p=[[Printer alloc]init];
NSLog(@"%@",p.getProductableTime);
//通过协议来定义变量
id<Output,Printable> outs =[[Printer alloc]init];
[outs addData:@"哈哈哈"];
[outs output];
NSLog(@"%@",[outs printColor]);
}
return 0;
}