Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an NSDictionary to an NSMutableDictionary?

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?

like image 588
Sheehan Alam Avatar asked Sep 05 '11 23:09

Sheehan Alam


People also ask

What is the difference between NSDictionary and NSMutableDictionary?

Main Difference is:NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary. NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).

What is the difference between NSMapTable vs NSDictionary?

NSDictionary / NSMutableDictionary copies keys, and holds strong references to values. NSMapTable is mutable, without an immutable counterpart. NSMapTable can hold keys and values with weak references, in such a way that entries are removed when either the key or value is deallocated.

What is NSMutableDictionary?

NSDictionary creates static dictionaries, and NSMutableDictionary creates dynamic dictionaries. (For convenience, the term dictionary refers to any instance of one of these classes without specifying its exact class membership.) A key-value pair within a dictionary is called an entry.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.


2 Answers

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.

like image 80
Dietrich Epp Avatar answered Sep 24 '22 10:09

Dietrich Epp


In case of Swift

var tempDic: NSMutableDictionary = yourDictionary.mutableCopy() as NSMutableDictionary 
like image 40
Developer Avatar answered Sep 22 '22 10:09

Developer