浅拷贝,深拷贝---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都会分配空间复制内容

 

posted on 2014-08-19 00:31  clarenceV1  阅读(194)  评论(0编辑  收藏  举报

导航