您的位置:首页 > 移动开发 > Objective-C

学习笔记(objective-c)-协议(proto 4000 col)

2015-06-20 16:58 447 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: