Reputation: 5076
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?
Upvotes: 9
Views: 22351
Reputation: 24267
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];
Upvotes: 1
Reputation: 1196
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
Upvotes: 13
Reputation: 112873
A NSMutableDictionary is a NSDictionary since it is a subclass. Typically the relationship of a subclass to it's superclass is called: "is a".
Upvotes: 3
Reputation: 3031
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
.
Upvotes: 6
Reputation: 483
NSMutableDictionary is a subclass of NSDictionary, so the writeToFile method should be available for your object without having to do any casting or conversions.
Upvotes: 7
Reputation: 5495
NSMutableDictionary inherits from NSDictionary. So, writeToFile should be available to both classes.
Upvotes: 14