深复制:复制对象时,如果对象中包含对象类型的实例变量,要对对象类型的实例变量也要做对象复制。新对象中的对象类型实例变量和旧对象中的对象类型实例变量指的是不同的对象。不管任何一方实例变量对对象做修改,都互相不影响对方所指向的对象的内容。
.h文件
1 // Person.h 2 // 03-对象复制 3 // 4 // Created by ma c on 15/8/14. 5 // Copyright (c) 2015年. All rights reserved. 6 // 7 8 #import <Foundation/Foundation.h> 9 10 @interface Person : NSObject<NSCopying> 11 @property(nonatomic,copy)NSMutableString *name;//(copy)深拷贝 12 @property(nonatomic,assign)NSInteger age; 13 -(id)initWithName:(NSMutableString*)name andAge:(NSInteger)age; 14 -(void)show; 15 @end
.m文件
// Person.m // 03-对象复制 // // Created by ma c on 15/8/14. // Copyright (c) 2015年. All rights reserved. // #import "Person.h" @implementation Person -(id)initWithName:(NSMutableString*)name andAge:(NSInteger)age { self = [super init]; if(self) { //复制对象有两种, //copy:复制出来的是一个不可变对象 //mutableCopy:复制出来的是一个可变对象 /* 对OC内置对象来说,内置类型有可变和不可变之分, 自定义的类没有这个区别,都是可变的。 */ _name = [name mutableCopy]; _age = age; } return self; } -(void)show { NSLog(@"name:%@,age:%lu",_name,_age); } -(void)dealloc { [_name release]; [super dealloc]; } -(id)copyWithZone:(NSZone *)zone { //深复制 //创建对象类型实例变量的副本 //NSMutableString *name = [_name copy]; return [[Person alloc]initWithName:_name andAge:_age]; } @end
.m主函数
1 // main.m 2 // 03-对象复制 3 // 4 // Created by ma c on 15/8/14. 5 // Copyright (c) 2015年. All rights reserved. 6 // 7 8 #import <Foundation/Foundation.h> 9 #import "Person.h" 10 int main(int argc, const char * argv[]) { 11 @autoreleasepool { 12 // 测试Person类 13 NSMutableString *name = [NSMutableString stringWithString:@"Tom"]; 14 15 Person *p1 = [[Person alloc]initWithName:name andAge:20]; 16 [p1 show]; 17 18 [name appendString:@"Jerry"]; 19 20 Person *p2 = [[Person alloc]initWithName:name andAge:21]; 21 [p2 show]; 22 23 [p1 show]; 24 25 //对象复制,自定义对象必须要实现NSCopying协议才能支持对象复制 26 Person *p3 = [p1 copy]; 27 [p3 show]; 28 29 [p1.name appendString:@"123"];//因为copy,p1和p2指向不同对象,互不影响 30 [p3 show]; 31 32 NSMutableString *name2 = [NSMutableString stringWithString:@"Jobs"]; 33 [p1 setName:name2];//p1和p3指向的是不同的对象,互不影响 34 [p3 show]; 35 36 [p1 release]; 37 [p2 release]; 38 [p3 release]; 39 } 40 return 0; 41 }
测试结果如下:
2015-08-14 16:54:53.912 03-对象复制[1512:99948] name:Tom,age:20 2015-08-14 16:54:53.913 03-对象复制[1512:99948] name:TomJerry,age:21 2015-08-14 16:54:53.913 03-对象复制[1512:99948] name:Tom,age:20 2015-08-14 16:54:53.913 03-对象复制[1512:99948] name:Tom,age:20 2015-08-14 16:54:53.914 03-对象复制[1512:99948] name:Tom,age:20 2015-08-14 16:54:53.914 03-对象复制[1512:99948] name:Tom,age:20 Program ended with exit code: 0
程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!
本文转自当天真遇到现实博客园博客,原文链接:http://www.cnblogs.com/XYQ-208910/p/4730533.html,如需转载请自行联系原作者