• 浅拷贝,深拷贝---ios


    #import <Foundation/Foundation.h>
    
    @interface Father : NSObject <NSCopying,NSMutableCopying>
    @property (nonatomic,copy) NSString *name;
    @property (nonatomic,retain) NSNumber *age;
    -(id) initWithName:(NSString *)name withAge:(NSNumber *) age;
    @end
    
    #import "Father.h"
    #import "Child.h"
    
    @implementation Father
    
    -(id) initWithName:(NSString *)name withAge:(NSNumber *) age{
        self=[super init];
        if(self!=nil){
            _name=name;
            _age=age;
        }
        return self;
    }
    //浅拷贝
    -(id) copyWithZone:(NSZone *)zone{
        Father *father=[[[self class] allocWithZone:zone] init];
        father.name=_name;
        father.age=_age;
        return father;
    }
    
    //深拷贝
    - (id)mutableCopyWithZone:(NSZone *)zone{
        Father *father=[[[self class] allocWithZone:zone] init];
        father.name=[_name mutableCopy];
        father.age=[_age copy];
        return self;
    }
    
     NSLog(@"-------自定义对象浅拷贝---------");
            //浅拷贝学习
            Father *father=[[Father alloc] initWithName:@"caitou" withAge:[NSNumber numberWithInt:23]];
            Father *father2=[father copy];
            NSLog(@"对象地址:%p",father);
            NSLog(@"对象地址:%p",father2);
            NSLog(@"对象属性地址name:%p",[father name]);
            NSLog(@"对象属性地址name:%p",[father2 name]);
            NSLog(@"对象属性地址age:%p",[father age]);
            NSLog(@"对象属性地址age:%p",[father2 age]);
            
             NSLog(@"--------自定义对象深拷贝---------");
            //深拷贝
            Father *father4=[[Father alloc] initWithName:@"caitou" withAge:[NSNumber numberWithInt:25]];
            Father *father3=[father4 mutableCopy];
            NSLog(@"对象地址:%p",father4);
            NSLog(@"对象地址:%p",father3);
            NSLog(@"对象属性地址name:%p",[father4 name]);
            NSLog(@"对象属性地址name:%p",[father3 name]);
            NSLog(@"对象属性地址age:%p",[father4 age]);
            NSLog(@"对象属性地址age:%p",[father3 age]);
            
            NSLog(@"-------浅拷贝---------");
            NSArray *array1=[[NSArray alloc] initWithObjects:@"sdf", nil];
            NSArray *array2=[array1 copy];
            NSLog(@"%p",array1);
            NSLog(@"%p",array2);
            
            NSLog(@"-------深拷贝---------");
            NSMutableArray *mutableArray=[NSMutableArray arrayWithObject:@"sdfdf" ];
            NSMutableArray *mutableArray2=[mutableArray mutableCopy];
            NSLog(@"%p",mutableArray);
            NSLog(@"%p",mutableArray2);
            //总结:当copy一个不可变对象时,相当有retain,即引用记数加一,其他情况copy,mutablecopy都会分配空间复制内容
    
  • 相关阅读:
    双屏显示器
    Cheat Engine Tutorial v3翻译Cheat Engine 6.1 tutorial(3)
    [转]VC6创建UNICODE版Windows程序
    fread
    [转]回调函数在MFC中的使用
    [转]C++ 虚函数表解析
    [转]C/C++返回内部静态成员的陷阱
    [转]EVC 中 include 的错误
    【rgw压缩】
    【ceph | 运维】rgw重置
  • 原文地址:https://www.cnblogs.com/clarence/p/3920944.html
Copyright © 2020-2023  润新知