Objective-C 语法五(协议)

来源:互联网 发布:html如何连接数据库 编辑:程序博客网 时间:2024/05/29 18:13

Objective-C 语法五(协议)

首先申明下,本文为笔者学习《Objective-C 基础教程》的笔记,并加入笔者自己的理解和归纳总结。

协议是包含了方法和属性的有名称列表。

1、创建协议

@protocol关键字声明了一个协议。
@protocol KeyListener- (void) onKeyDown;- (void) onKeyUp;@end

2、协议可以继承父协议。

@protocol MouseListener <KeyListener>- (void) onKeyMove;@end

3、协议中的关键字

@required:表示必须强制实现的方法
@optional:表示可以有选择性的实现方法

4、实现协议

NSCopying协议是对对象进行拷贝的协议。
Shape实现协议NSCopying,实现方法copyWithZone。Rectangle继承了Shape,同样实现方法copyWithZone。

@interface Shape : NSObject <NSCopying>@property int width;@property int height;@end@implementation Shape @synthesize width;@synthesize height;- (id) init {if (self = [super init]) {width = 20;height = 20;NSLog(@"Shape init");}return self;}- (id) copyWithZone: (NSZone *)zone {Shape* shapeCopy = [[[self class]allocWithZone:zone] init];shapeCopy.width = width;shapeCopy.height = height;return shapeCopy;}- (NSString*) description {return [NSString stringWithFormat: @"(%d, %d)",[self width], [self height]];}@end@interface Rectangle : Shape@property int radius;@end@implementation Rectangle @synthesize radius;- (id) copyWithZone: (NSZone *)zone {Rectangle* rectangleCopy = [super copyWithZone: zone];rectangleCopy.radius = [self radius];return rectangleCopy;}- (NSString*) description {return [NSString stringWithFormat: @"(%d, %d) radius = %d",[self width], [self height], [self radius]];}@endint main(int argc, const char* argv[]) {@autoreleasepool {Shape* shape = [[Shape alloc] init];shape.width = 30;shape.height = 20;NSLog(@"%@", [shape copy]);Rectangle* rect = [[Rectangle alloc] init];rect.width = 100;rect.height = 60;rect.radius = 5;NSLog(@"%@", [rect copy]);}return 0;}

原创粉丝点击