首页 > 代码库 > 【Object-C】Copy

【Object-C】Copy


-copyWithZone:
Returns a new instance that’s a copy of the receiver. (required)
-mutableCopy
Returns the object returned by mutableCopyWithZone: where the zone is nil.

Declaration:
- (id)copyWithZone:(NSZone *)zone
- (id)mutableCopy

简单的说,copy方法用于复制对象的副本,并返回对象的不可变副本(即使对象本身可变)。
mutablecopy方法则用于复制对象的可变副本,总是返回对象的可变副本(即使被复制对象的本身是不可变的)。
当程序对复制的原对象副本进行修改时,原对象不会受到影响。
//
//  main.m
//  NeuCopy
//
//  Created by mac on 14-12-1.
//  Copyright (c) 2014mac. All rights reserved.
//

#import<Foundation/Foundation.h>
#import
"People.h"
#import
"Dog.h"
#import
"GoodPeople.h"

/*
 
copy
意义对于非可变对象来说,并不是产生新的对象,
而对于可变对象来说,是产生一个新的对象
 
multablecopy
 
对于非可变对象的话,也是产生一个可变对象,
对于可变对象来说,自然也是产生一个可变对象
 

*/


intmain(intargc, const char * argv[]) {
   
@autoreleasepool {
       
       
//alloc方法新建一个p1对象
       
People * p1 = [[Peoplealloc]init];
        p1.
age= 45;//设置age属性
       
       
//使用copy方法复制p2对象
       
People * p2 = [p1 copy];
        p2.
age= 32;
       
//输出p1p2及其属性
       
NSLog(@"实例对象p1:%@,p1的副p2:%@, %i,%i",p1,p2,p1.age,p2.age);
       
       
//分别用alloccopyretain方法创建对象。
       
Dog * dog1 = [[Dogalloc]initWithColor:4];
       
Dog * dog2 =  [dog1copy];
       
Dog * dog3 = [dog1 retain];
       
//查看对象返回值
       
NSLog(@"%@ ,%@ , %@ ,%i, %i",dog1,dog2,dog3,dog1.color,dog2.color);
       
       
     
       
Dog * dog = [[Dogalloc]init];
       
GoodPeople * gp = [[GoodPeoplealloc]init];
       
        gp.
dog= dog;
       
GoodPeople * gp1 = [gpcopy];
       
NSLog(@"dog:%@, gp:%@, gp1:%@",dog,gp.dog,gp1.dog);
        gp1.
sex= 0;
       
       
//释放内存
        [dog
release];
        [gp
release];
        [gp1
release];
        [p1
release];
        [p2
release];
       
    }
   
return 0;
}

#import"People.h"
@implementationPeople

-(
id)copyWithZone:(NSZone*)zone
{
     
//深拷贝,为copy副本申请新的内存空间
//    People *p = [[self class] allocWithZone:zone];
//   
//    p.age = self.age;
//   
//    return p;
   
//浅拷贝,将copy副本的self指针指向原对象的内存地址,原对象和副本地址将会是同一个
   
return  [selfretain];
}
@end
===>
2014-12-01 18:32:22.882 NeuCopy[3013:303]实例对象p1:<People: 0x100102300>,p1的副p2:<People: 0x100102300>, 32,32
2014-12-01 18:32:22.884 NeuCopy[3013:303] <Dog: 0x1006013b0> ,<Dog: 0x100602290> , <Dog: 0x1006013b0> ,4, 4
2014-12-01 18:32:22.885 NeuCopy[3013:303] dog:<Dog: 0x10010a050>, gp:<Dog: 0x10010bac0>, gp1:<Dog: 0x10010bac0>
2014-12-01 18:32:22.886 NeuCopy[3013:303] dog is releaseing
2014-12-01 18:32:22.886 NeuCopy[3013:303] dog is releaseing
Program ended with exit code: 0

【Object-C】Copy