I have an NSMutableDictionary called source, and then I create another this way:
NSMutableDictionary *new = [source copy];
But when I modify one of new‘s values, the value of source is also modified. Why is that?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The problem is that iOS (and OSX) use shallow copies. That means the new collection has the same objects in it as the original. As the @danDedo said in his answer, your copy is non-mutable – that it, its a dictionary not a mutable dictionary (so you could not add or delete objects). But the objects are the same. So if these objects are themselves mutable, then changes in one place will affect all references (that is, all the objects in the copies).
The solution to this is to write your own “deep copy” (if you need it) – you can for sure find examples searching for “deep copy” here.