首先申明下,本文为笔者学习《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]];
}
@end
int main(int argc, const char* argv[]) {
@autoreleasepool {
Shape *shape = [[Shape alloc] init];
shape.width = 30;
shape.height = 25;
NSLog(@"%@", [shape copy]);
Rectangle *rect = [[Rectangle alloc] init];
rect.width = 100;
rect.height = 60;
rect.radius = 5;
NSLog(@"%@", [rect copy]);
}
return 0;
}
输出
Shape init
Shape init
(30, 25)
Shape init
Shape init
(100, 60) radius = 5