码迷,mamicode.com
首页 > 移动开发 > 详细

浅拷贝,深拷贝---ios

时间:2014-08-19 00:57:13      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:blog   os   io   ar   div   log   on   sp   

#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都会分配空间复制内容

 

浅拷贝,深拷贝---ios,布布扣,bubuko.com

浅拷贝,深拷贝---ios

标签:blog   os   io   ar   div   log   on   sp   

原文地址:http://www.cnblogs.com/clarence/p/3920944.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!