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的类型决定的,不是声明的类型。

你可能感兴趣的:(Objective-C,NSCopying)