Reputation: 492
I am new to Objective C and I had no idea that in an NS(Mutable)Dictionary I must use (mutable)Copy
for an assignment like this:
dict[@"backup"] = dict[@"myList"];
Using debugging I found out that the assignment must be done like this:
dict[@"backup"] = [dict[@"myList"] mutableCopy];
Now the question is: how do I know that I must use copies (vs references) and for which type of objects?
Thank you!
Upvotes: 0
Views: 35
Reputation: 52622
There is nothing that you must do.
A dictionary contains key-value pairs. For example, for your code to work, dict contains some object as the value for the key "myList". No idea what that object is. You can make three different assignments, and each is perfectly valid but does something different:
dict [@"backup"] = dict [@"myList"];
stores the same object that is already there under the key myList under the key backup as well. If the object is mutable, and someone modifies the object, then the object under each key is modified, because it is the same object.
dict [@"backup"] = [dict [@"myList"] copy];
"copy" is interesting. Usually it will create a copy of the object, so you have two objects, an old one and a new one. If the original is mutable, then the copy will be immutable. But if the original is immutable, then the OS assumes that there is no point in making a copy, so copy will give the original object. Anyway, dict [@"backup"] will be an immutable object that cannot be affected by modifications to dict [@"myList"], either because it is not the same object, or because dict [@"myList"] cannot be modified.
dict [@"backup"] = [dict [@"myList"] mutableCopy];
This makes a mutable copy of the original and stores it. It is definitely not the same object. And it can be modified.
It really depends on what you want to achieve. There is no right or wrong here.
Upvotes: 3
Reputation: 36323
Simply it depends on the use of the assigned element. If you are going to change its content it must be mutable. If you are just reading it, don't make it mutable.
Upvotes: 1