0
NSMutableDictionary *dic0 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"string0", @"key0", nil];
NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"string1", @"key1", nil];
NSDictionary *dic2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"string2", @"key2", nil];
NSDictionary *dic3 = [[NSDictionary alloc] initWithObjectsAndKeys:@"dic3", @"key3", nil];

NSArray *arrayOri = [[NSArray alloc] initWithObjects:dic0, dic1, dic2, nil];

//here means a deep copy
NSMutableArray *arrayDeepCopy = [[NSMutableArray alloc] initWithArray:arrayOri copyItems:YES];

NSRange range = {0, 2};
NSArray *subArray = [arrayOri subarrayWithRange:range];
[arrayDeepCopy addObject:dic3];

NSLog(@"arrayOri not merge %@", arrayOri);

//merge one object
[dic0 setObject:@"mutableV" forKey:@"mutableKey"];
//dealloc one object
[dic1 dealloc];

NSLog(@"arrayOri %@  ", arrayOri);
NSLog(@"subArray %@  ", subArray);

在这里崩溃,因为 dic1 已解除分配,如果是深拷贝,为什么原始对象对新对象有影响?

NSLog(@"array %@  ", arrayDeepCopy);

what initWithArray:(NSArray *)array copyItems:(BOOL)flag  do after all??
4

1 回答 1

0

问题是这dic1是一个不可变的对象。因此将它复制到内存中是没有意义的,因此arrayDeepCopy持有指向原始dic1对象的指针。当您释放它时,它会从存储它的所有数组中消失。
如果你想要一个真正的深拷贝,你必须实例化一个NSMutableDictionary.

于 2013-05-09T08:32:02.280 回答