标签:
NSString *a = [[NSString alloc]initWithString:@"hello"];
NSString *b = [a copy];
NSLog(@"%d %d",a.retainCount, b.retainCount);// 2,2
NSMutableString *f = [a mutableCopy];
NSLog(@"%d %d",a.retainCount, f.retainCount);// 2,1
[f appendString:@"dd"];
NSLog(@"%@,%@",a,f);// hello,hellodd
// 对于一个不可变对象来说 copy 是浅copy 只是指针复制 其retainCount 1
// mutablecopy 是深copy 是对象复制
NSMutableString *c = [[NSMutableString alloc]initWithString:@"hello"];
NSMutableString *d = [c copy];
NSLog(@"%d %d",c.retainCount,d.retainCount);// 1,1
// [d appendString:@"ddd"]; //error 因为copy返回一个不可改变对象
NSMutableString *e = [c mutableCopy];
NSLog(@"%d %d",c.retainCount,e.retainCount);// 1,1
[e appendString:@"dddd"];
NSLog(@"%@,%@",c,e);// hello,hellodddd
// 对于可变对象来说 copy 和mutablecopy 都是深copy 都是拷贝对象 不过copy返回的对象是一个不可变对象
//------------------------------------------------------------//
// 对于系统容器类对象
NSArray *array1 = [NSArray arrayWithObjects:@"a",@"b",@"c",nil];
NSArray *array1Copy = [array1 copy];
NSLog(@"%d, %d",array1.retainCount,array1Copy.retainCount);//2,2
NSMutableArray *arrayMcopy = [array1 mutableCopy];
NSLog(@"%d, %d",array1.retainCount,arrayMcopy.retainCount);//2,1
[arrayMcopy removeObjectAtIndex:0];
[arrayMcopy addObject:@"d"];
NSLog(@"%@-----%@",array1,arrayMcopy);//a,b,c -----b,c,d
NSArray *mArray1 = [NSArray arrayWithObjects:[NSMutableString stringWithString:@"a"],@"b",@"c",nil];
NSArray *mArray1copy = [mArray1 copy];
NSLog(@"%d,%d",mArray1.retainCount,mArray1copy.retainCount);//2,2
NSMutableArray *mArrayMcopy = [mArray1 mutableCopy];
NSLog(@"%d,%d",mArray1.retainCount,mArrayMcopy.retainCount);//2,1
NSMutableString *temp = [mArray1 objectAtIndex:0];
NSLog(@"%@",temp);//a
[temp appendString:@"aa"];
NSLog(@"%@",mArray1);//aaa b c
NSLog(@"%@",mArray1copy); //aaa b c
NSLog(@"%@",mArrayMcopy);// aaa b c
//对于容器而言,其元素对象始终是指针复制。如果需要元素对象也是对象复制,就需要实现深拷贝。
NSArray* trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData:
[NSKeyedArchiver archivedDataWithRootObject: mArray1]];
NSMutableString *temp2 = [trueDeepCopyArray objectAtIndex:0];
[temp2 appendString:@"aa"];
NSLog(@"%@",mArray1);//aaa b c
NSLog(@"%@",trueDeepCopyArray);//aaaaa b c
//trueDeepCopyArray是完全意义上的深拷贝
标签:
原文地址:http://www.cnblogs.com/chengxianghe/p/4305036.html