9

I would like to use a method (writeToFile) only available for NSDictionary to a NSMutableDictionary object. So, how do I convert this NSMutableDictionary object to NSDictionary?

Wayne
  • 59,728
  • 15
  • 131
  • 126
Stephane
  • 4,978
  • 9
  • 51
  • 86

6 Answers6

14

NSMutableDictionary inherits from NSDictionary. So, writeToFile should be available to both classes.

Daryl Teo
  • 5,394
  • 1
  • 31
  • 37
13

For those coming here genuinely looking for conversion from NSMutableDictionary to NSDictionary :

NSMutableDictionary *mutableDict = [[[NSDictionary alloc] initWithObjectsAndKeys:
                              @"value", @"key"] mutableCopy];

NSDictionary *dict = [NSDictionary dictionaryWithDictionary:mutableDict]; //there you have it
Yoga
  • 1,186
  • 1
  • 13
  • 24
7

NSMutableDictionary is a subclass of NSDictionary, so the writeToFile method should be available for your object without having to do any casting or conversions.

Jeremy Flores
  • 483
  • 4
  • 8
6

As already discussed here:

How to save a NSMutableDictionary into a file in documents?

you don't need to convert it.

But if you really want to, just use the copy method on your NSMutableDictionary or the dictionaryWithDictionary: method on NSDictionary. Both provide an NSDictionary from an NSMutableDictionary.

Community
  • 1
  • 1
adpalumbo
  • 3,031
  • 12
  • 12
3

A NSMutableDictionary is a NSDictionary since it is a subclass. Typically the relationship of a subclass to it's superclass is called: "is a".

zaph
  • 111,848
  • 21
  • 189
  • 228
1

To address the actual question title and not the contents (since I searched for this Q) you can actually rely on copyWithZone: to get down to an Immutable Dictionary.

NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] init];
mutableDict[@"key"] = @"value";
NSDictionary *immutableDict = [mutableDict copy];
Daniel Galasko
  • 23,617
  • 8
  • 77
  • 97