zoukankan      html  css  js  c++  java
  • NSCopying协议和copy方法

    不是所有的对象都支持 copy
    需要继承NSCopying 协议(实现 copyWithZone: 方法)
    同样,需要继承NSMutableCopying 协议才可以使用mutableCopy(实现 mutableCopyWithZone: 方法)

    默认 NSObject没有实现这两个协议,但是 copy和mutableCopy这两个方法是NSObject定义的

    这里要列举范例

    //1.h
    @interface CommonObj : NSObject<NSCopying>
     
    @end
     
    @interface MyCObj : NSObject<NSCopying>
    @property (nonatomic ,copy) CommonObj *obj;
    @end
     
    //1.m
    @implementation CommonObj
     
    - (id)init
    {
        self = [super init];
        if (self)
        {
        }
     
        return self;
    }
     
    - (void)dealloc
    {
        [super dealloc];
    }
     
    - (id)copyWithZone:(NSZone *)zone
    {
        CommonObj *result = [[[self class] allocWithZone:zone] init];
        return result;
    }
    @end
     
    @implementation MyCObj
     
    @synthesize obj = _obj;
     
    - (id)init
    {
        self = [super init];
        if (self)
        {
            self->_obj = nil;
        }
     
        return self;
    }
     
    - (void)dealloc
    {
        if (self.obj)
            [self->_obj release];
     
        [super dealloc];
    }
     
    - (id)copyWithZone:(NSZone *)zone
    {
        MyCObj *result = [[[self class] allocWithZone:zone] init];
     
        result->_obj = [self->_obj copy];
     
        return result;
    }
    @end
     
    //main.m
     
    - (void)Test
    {
        CommonObj *a1 = [[CommonObj alloc] init];
        CommonObj *a2 = [a1 copy];
     
        MyCObj *b1 = [[MyCObj alloc] init];
        MyCObj *b2 = [b1 copy];
        [b2 release];
        [b1 release];
     
        [a2 release];
        [a1 release];
    }

     打印上述对象的地址,就会发现地址各不相同,retaincount = 1;

    这里要注意类似NSString的类,比如:NSArray

    NSString *t1 = @"hello";
    NSString *t2 = [t1 copy];

    打印地址,两个地址一模一样;NSArray对象也是同样。之所以会是同一地址,估计在常量或不可变这个属性上

    小结:
    这个就是C++下的拷贝构造函数的另类描述,目的在于拷贝。至于实现的拷贝是深度拷贝还是浅度拷贝,这是由实现者设计

  • 相关阅读:
    WPF 使用 Direct2D1 画图 绘制基本图形
    WPF 使用 Direct2D1 画图 绘制基本图形
    dot net core 使用 IPC 进程通信
    dot net core 使用 IPC 进程通信
    win2d 图片水印
    win2d 图片水印
    Java实现 LeetCode 240 搜索二维矩阵 II(二)
    PHP closedir() 函数
    PHP chroot() 函数
    PHP chdir() 函数
  • 原文地址:https://www.cnblogs.com/lingzhao/p/3432528.html
Copyright © 2011-2022 走看看