浅复制:复制对象时,如果对象中包含对象类型的实例变量,只是复制指针。新对象中的对象类型实例变量和旧对象中的对象类型实例变量指的是同一个对象。任何一方实例变量对对象做修改,另一方实例变量指向的该对象也就改变了。
.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>//实现NSCopying协议才能支持自定义对象的复制
11 @property(nonatomic,retain)NSMutableString *name;//(retain)浅拷贝,拷贝对象的引用,其实用的还是一个对象,相当于一个人给自己起了一个别名
12 @property(nonatomic,assign)NSInteger age;
13 -(id)initWithName:(NSMutableString*)name andAge:(NSInteger)age;
14 -(void)show;
15 @end
.m实现文件
1 // Person.m
2 // 03-对象复制
3 //
4 // Created by ma c on 15/8/14.
5 // Copyright (c) 2015年. All rights reserved.
6 //
7
8 #import "Person.h"
9
10 @implementation Person
11 -(id)initWithName:(NSMutableString*)name andAge:(NSInteger)age
12 {
13 self = [super init];
14 if(self)
15 {
16 _name = [name retain];//强引用,获得对象所有权
17 _age = age;
18 }
19 return self;
20 }
21 -(void)show
22 {
23 NSLog(@"name:%@,age:%lu",_name,_age);
24 }
25 -(void)dealloc
26 {
27 [_name release];
28 [super dealloc];
29 }
30 -(id)copyWithZone:(NSZone *)zone
31 {
32 return [[Person alloc]initWithName:_name andAge:_age];
33 }
34 @end
main.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"];//因为retain,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:40:59.293 03-对象复制[1460:96685] name:Tom,age:20 2015-08-14 16:40:59.294 03-对象复制[1460:96685] name:TomJerry,age:21 2015-08-14 16:40:59.294 03-对象复制[1460:96685] name:TomJerry,age:20 2015-08-14 16:40:59.295 03-对象复制[1460:96685] name:TomJerry,age:20 2015-08-14 16:40:59.295 03-对象复制[1460:96685] name:TomJerry123,age:20 2015-08-14 16:40:59.295 03-对象复制[1460:96685] name:TomJerry123,age:20 Program ended with exit code: 0
程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!
本文转自当天真遇到现实博客园博客,原文链接:http://www.cnblogs.com/XYQ-208910/p/4730496.html,如需转载请自行联系原作者