How do I use the writeToFile method on an NSMutableDictionary?
Asked Answered
S

6

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?

Smokejumper answered 19/9, 2011 at 23:59 Comment(0)
J
14

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

Jinja answered 20/9, 2011 at 0:3 Comment(0)
L
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
Loreanloredana answered 16/8, 2015 at 13:46 Comment(0)
A
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.

Airbrush answered 20/9, 2011 at 0:4 Comment(0)
Q
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.

Quantic answered 20/9, 2011 at 0:5 Comment(0)
F
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".

Fourway answered 20/9, 2011 at 3:23 Comment(0)
C
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];
Charter answered 3/3, 2016 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.