学习笔记(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
例:
#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
相关文章推荐
- [玩玩Objective-C]之动态绑定
- New XAMPP security concept: Access to the requested object is only available from the local network
- Objective-C 语法之 Debug 表达式
- Objective-C----内存管理
- Objective-c 算术函数和常量代表
- Objective-C----NSDate、NSDateFormatter
- Objective-C----多态
- Objective-C----autorelease pool
- Objective-C----Block 、数组排序
- Objective-C----快速枚举、数组排序
- Objective-C----NSSet 、 NSMutableSet 、 NSCountedSet
- Objective-C----NSString 、 NSMutableString
- Objective-C----NSDictionary、NSMutableDictionary
- Objective-C----NSArray、NSMutableArray
- [玩玩Objective-C]之类和对象
- Object.create(): the New Way to Create Objects in JavaScript
- Object properties in JavaScript
- How to list the properties of a JavaScript object
- Swift项目中调用Objective-C的库
- Objective-C 语法之 NSURL