objective-c中的协议是多个类共同的行为规范,协议里是定义一组公用方法,通过类来实现这些方法。
例:
#import <Foundation/Foundation.h>
//定义协议
@protocol APPLEPrintable
-(void) output;
-(NSDate*) getProduceTime;
@end
#import "APPLEPrintable.h"
//定义类继承NSObject,遵守APPLEPrintable协议
@interface APPLEPrinter : NSObject <APPLEPrintable>
@end
#import "APPLEPrinter.h"
#import <Foundation/FOundation.h>
@implementation APPLEPrinter
-(void) output
{
NSLog(@"the method output");
}
-(NSDate*) getProduceTime;
{
return [[NSDate alloc]init];
}
@end
int main(int argc,char* argv[])
{
@autoreleasepool{
APPLEPrinter* printer = [[APPLEPrinter alloc]init];
[printer output];
NSLog(@"%@",[printer getProduceTime]);
}
}
正式协议与非正式协议的区别如下:
正式协议:必须实现协议中的方法。
非正式协议:可不实现协议中方法。(为NSObject创建类别实现)
如果正式协议要不实现其中的方法:
则需要加@optional关键字。
例:
@protocol APPLE
@optiona
//该方法可以不实现
@end
@required
//该方法需要要实现
@end