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);

crash here,because of dic1 dealloced,if deep copy,why the original object has an effect with new object??

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

what initWithArray:(NSArray *)array copyItems:(BOOL)flag  do after all??
1
  • You need to explain your question better. Please don't just paste code with comments. These are easily overlooked. Ask a question with examples, please read the faq and tour
    – Liam
    Commented May 9, 2013 at 7:33

1 Answer 1

0

The problem is that dic1 is an immutable object. Thus is does not make sense to copy it in memory, and therefore arrayDeepCopy holds a pointer to the original dic1 object. When you deallocate it, it is gone from all arrays that store it.
If you want to have a true deep copy, you have to instantiate a NSMutableDictionary.

1
  • @user2365237: I did not get any response to my answer. So, if it solved your problem, please consider accepting it. If there is still a problem, please add a comment. Commented May 12, 2013 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.