NSCopying协议练习

#import <Foundation/Foundation.h>

@interface TestCopyProtocol : NSObject<NSCopying>

@property (nonatomic,readwrite) NSInteger index;
@property (nonatomic,readwrite,copy) NSString* str;

- (id)copyWithZone:(NSZone *)zone;
- (NSString *)description;

@end

@interface TestCopyProtocolChild : TestCopyProtocol<NSCopying>

@property(nonatomic,readwrite,copy) NSString* myStr;

- (id)copyWithZone:(NSZone *)zone;
- (NSString *)description;
@end
#import "TestCopyProtocol.h"
#import <UIKit/UIKit.h>
@implementation TestCopyProtocol

-(id)copyWithZone:(NSZone *)zone
{
    id copy = [[[self class] alloc] init];
    
    if (copy) {
        [copy setIndex:self.index];
        [copy setStr:self.str];
    }
    return copy;
}

-(NSString*)description
{
    return [NSString stringWithFormat:@"super des is %@ int is %ld, str is %@",
           [super description], self.index, self.str];
}

@end

@implementation TestCopyProtocolChild
-(id)copyWithZone:(NSZone *)zone
{
    id copy = [super copyWithZone:zone];
    if (copy) {
        [copy setMyStr:self.myStr];
    }
    return copy;
}

-(NSString*)description
{
    return [NSString stringWithFormat:@"super des is %@ myStr is %@",
            [super description], self.myStr];
}
@end
调用
    TestCopyProtocol* t = [[TestCopyProtocol alloc]init];
    t.index = 5;
    t.str = @"hello";
    TestCopyProtocol* t1 = [t copy];
    t.str = @"world";
    NSLog(@"%@",t);
    NSLog(@"%@",t1);
    
    
    TestCopyProtocolChild* t2 = [t copy];
    NSLog(@"%@",t2.class);//这个地方是个坑吧,t2怎么就变成了TestCopyProtocol?
    TestCopyProtocolChild* t3 = [[TestCopyProtocolChild alloc] init];
    t3.index = 4;
    
    t3.myStr = @"w";
    TestCopyProtocolChild* t4 = [t3 copy];
    NSLog(@"%@",t4);

总结下吧:

        1,写这个协议的时候,得看下类的上层类(可能是父类以上的类)有没有实现这个方法copyWithZone,也就是找到alloc对象的地方。

        2,如果父类实现了这个协议,子类就不用写了,直接覆盖copyWithZone即可(协议的实现应该都是这样吧,和接口道理类似)。

        3,调用的时候,对象变量的类型是根据被copy的类型决定的,不是声明的类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值