nsdictionary copy vs mutable copy
Asked Answered
H

1

5

I have

NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];
id dict = [myDictionary copy];

but is dict now just a regular NSDictionary? Or is it a copy of the NSMutableDictionary?

Also, is there any way to go from mutable to non-mutable?

Hardboard answered 22/4, 2012 at 17:35 Comment(0)
S
18

There are two methods involved here; -copy and -mutableCopy.

If the class holds a distinction; -copy always creates an immutable copy; and -mutableCopy always creates a mutable copy.

If the class holds no distinction; -copy always creates a true copy.

So yes, dict is now an NSDictionary, containing the objects in the dictionary.

Sahib answered 22/4, 2012 at 17:49 Comment(8)
Minor correction: copy does not create a deep copy, so the objects in the copied dictionary will be the same as those in the original one, not copies.Mellman
@omz: Does that also apply if the contents of the dictionary adopt NSCopying?Sahib
The Cocoa collection classes always do a shallow copy for the -copy method.Cytokinesis
Yes, you would have to explicitly use initWithDictionary:copyItems: to create a deep copy.Mellman
@WillihamTotland: Yes. The objects in the dictionary make no difference; the copy is always shallow.Meticulous
@Williham Totland : hi..can you please explain what do you mean by " class holds distinction".... thanks in advance.Prady
@Cultor: I feel the meaning of the word should be clear from my answer.Sahib
@Williham Totland : hi, actually I'm a beginner, so didn't understand.Prady

© 2022 - 2024 — McMap. All rights reserved.