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 dealloced,如果深拷贝,为什么原始对象对新对象有效?
NSLog(@"array %@ ", arrayDeepCopy);
what initWithArray:(NSArray *)array copyItems:(BOOL)flag do after all??
答案 0 :(得分:0)
问题是dic1
是一个不可变对象。因此将它复制到内存中是没有意义的,因此arrayDeepCopy
保存指向原始dic1
对象的指针。当你解除分配它时,它会从存储它的所有数组中消失
如果您想拥有真正的深层副本,则必须实例化NSMutableDictionary
。