ios下的深拷贝和浅拷贝,copy && mutableCopy
其中 Model继承自NSObject ,看看log,可能有你想不到的结果
Model * model = [[Model alloc] init];
NSLog(@"model rc=%d",[model retainCount]);
NSArray * oriArray = [NSArray arrayWithObjects:model,@"a",@"b", nil];//源数据,不可修改
NSLog(@"model rc=%d,oriArray rc=%d",[model retainCount],[oriArray retainCount]);
NSArray * oriArrayCopy = [oriArray copy];//跟oriArray地址一样,浅拷贝,不可修改
NSLog(@"model rc=%d,oriArray rc=%d,oriArrayCopy rc=%d",[model retainCount],[oriArray retainCount],[oriArrayCopy retainCount]);
NSArray * oriArrayMCopy = [oriArray mutableCopy];//深拷贝,生成了NSMutableArray,可以修改
NSLog(@"model rc=%d,oriArray rc=%d,oriArrayCopy rc=%d,oriArrayMCopy rc=%d",[model retainCount],[oriArray retainCount],[oriArrayCopy retainCount],[oriArrayMCopy retainCount]);
NSLog(@"oriArray =%p ,0 =%p",oriArray,[oriArray objectAtIndex:0]);
NSLog(@"oriArrayCopy =%p ,0 =%p ",oriArrayCopy,[oriArrayCopy objectAtIndex:0]);
NSLog(@"oriArrayMCopy =%p ,0 =%p ",oriArrayMCopy,[oriArrayMCopy objectAtIndex:0]);
NSLog(@"++++++");
Model * model2 = [[Model alloc] init];
NSLog(@"model rc=%d",[model2 retainCount]);
NSMutableArray *oriMArray = [NSMutableArray arrayWithObjects:model2,@"a", @"b",nil];//源数据,可以修改
NSLog(@"model rc=%d,oriMArray rc=%d",[model2 retainCount],[oriMArray retainCount]);
NSMutableArray *oriMArrayCopy = [oriMArray copy];//深拷贝,生成不可变的NSArray
NSLog(@"model rc=%d,oriMArray rc=%d,oriMArrayCopy rc=%d",[model2 retainCount],[oriMArray retainCount],[oriMArrayCopy retainCount]);
NSMutableArray *oriMArrayMCopy = [oriMArray mutableCopy];//深拷贝,可以修改
NSLog(@"model rc=%d,oriMArray rc=%d,oriMArrayCopy rc=%d,oriMArrayMCopy rc=%d",[model2 retainCount],[oriMArray retainCount],[oriMArrayCopy retainCount],[oriMArrayMCopy retainCount]);
// NSMutableArray *oriMArrayMCopy2 = [[NSMutableArray alloc] initWithArray:oriMArray copyItems:YES];
NSLog(@"oriMArray =%p, 0 =%p",oriMArray,[oriMArray objectAtIndex:0]);
NSLog(@"oriMArrayCopy =%p, 0 =%p ",oriMArrayCopy,[oriMArrayCopy objectAtIndex:0]);
NSLog(@"oriMArrayMCopy =%p, 0 =%p ",oriMArrayMCopy,[oriMArrayMCopy objectAtIndex:0]);
//NSLog(@"oriMArrayMCopy2 0 =%p c=%d",[oriMArrayMCopy2 objectAtIndex:0],[[oriMArrayMCopy2 objectAtIndex:0] retainCount]);
结果
model rc=1
model rc=2,oriArray rc=1
model rc=2,oriArray rc=2,oriArrayCopy rc=2
model rc=3,oriArray rc=2,oriArrayCopy rc=2,oriArrayMCopy rc=1
oriArray =0x8a6d380 ,0 =0x8a6cc50
oriArrayCopy =0x8a6d380 ,0 =0x8a6cc50
oriArrayMCopy =0xa23f940 ,0 =0x8a6cc50
++++++
model rc=1
model rc=2,oriMArray rc=1
model rc=3,oriMArray rc=1,oriMArrayCopy rc=1
model rc=4,oriMArray rc=1,oriMArrayCopy rc=1,oriMArrayMCopy rc=1
oriMArray =0x8a5cac0, 0 =0x8e5edb0
oriMArrayCopy =0x8e59440, 0 =0x8e5edb0
oriMArrayMCopy =0x8c3e990, 0 =0x8e5edb0