45

I have an existing NSDictionary that has:

{
    "charts_count" = 2;
    "created_at" = "2010-04-12T16:37:32Z";
    exchange = NASDAQ;
    "followers_count" = 259;
    id = 8404;
    industry = "<null>";
    "messages_count" = 1436;
    ric = "GRPN.O";
    sector = "<null>";
    symbol = GRPN;
    title = Groupon;
    "updated_at" = "2011-09-05T04:17:56Z";
}

How can I take these contents and put it into a new NSMutableDictionary?

Sheehan Alam
  • 60,111
  • 124
  • 355
  • 556
  • 1
    possible duplicate of [Set an NSMutableDictionary variable to an NSDictionary](http://stackoverflow.com/questions/4116031/set-an-nsmutabledictionary-variable-to-an-nsdictionary) – jscs Sep 06 '11 at 00:03

4 Answers4

137

Use -mutableCopy.

NSDictionary *d;
NSMutableDictionary *m = [d mutableCopy];

Note that -mutableCopy returns id (Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • 3
    It should be noted that this will not inherently make the dictionary objects also mutable so if you have a dictionary of arrays of more dictionaries the children will not become mutable. – Vlad Jun 18 '15 at 01:53
  • @Vlad - I want to achieve exactly What you said, Need to Make inherently make the dictionary objects also mutable i.e. all children objects of the dictionary should become mutable. – Anand Mar 04 '21 at 04:40
  • @Vlad - I wanted to achieve what you said, have a dictionary that has an array and other dictionaries, need to make all children mutable inherently. – Anand Mar 04 '21 at 06:20
8

In case of Swift

var tempDic: NSMutableDictionary = yourDictionary.mutableCopy() as NSMutableDictionary
Developer
  • 6,375
  • 12
  • 58
  • 92
2

Try this in swift 3

let mutableDic: NSMutableDictionary =  (yourDictionary as! NSDictionary).mutableCopy() as! NSMutableDictionary
Sreeraj VR
  • 1,524
  • 19
  • 35
1
NSMutableDictionary *newInfo = [[NSMutableDictionary alloc] init];
[newInfo setDictionary:info];

Also works, since you are setting the dictionary not appending. You can also use:

[newInfo addEntriesFromDictionary:info];

for the same effect and to append to existing content.

Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71