iOS 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]];
}

@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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值