我正在尝试为 NSMutableArray 实现深浅复制,
self.oldArray =[[NSMutableArray alloc] initWithCapacity:0];
self.shallowCopy =[[NSMutableArray alloc] initWithCapacity:0];
self.deepCopy =[[NSMutableArray alloc] initWithCapacity:0];
//add object to old Array
[self.oldArray addObject:@"rooban"];
[self.oldArray addObject:@"radha"];
[self.oldArray addObject:@"jesus"];
[self.oldArray addObject:@"god"];
self.shallowCopy=[[NSMutableArray alloc] initWithArray:self.oldArray];
self.deepCopy=[[NSMutableArray alloc] initWithArray:self.oldArray copyItems:YES];
//deep copy
NSLog(@"Lenght of the Old Array before: %d",self.deepCopy.count);
[self.deepCopy removeObject:@"rooban"];
NSLog(@"Lenght of the Old Array After: %d",self.oldArray.count);
//shallow copy
NSLog(@"Lenght of the Old Array Before: %d",self.shallowCopy.count);
[self.shallowCopy removeObject:@"rooban"];
NSLog(@"Lenght of the Old Array After: %d",self.oldArray.count);
这个程序的输出是,
深拷贝:
之前的旧数组的长度:4
之后的旧数组的长度:4
浅拷贝:
旧数组之前的长度:4
旧数组之后的长度:4
我不知道为什么浅拷贝删除没有反映到原始 NSMutableArray。