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?
NSMutableDictionary inherits from NSDictionary. So, writeToFile should be available to both classes.
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
NSMutableDictionary is a subclass of NSDictionary, so the writeToFile method should be available for your object without having to do any casting or conversions.
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
.
A NSMutableDictionary is a NSDictionary since it is a subclass. Typically the relationship of a subclass to it's superclass is called: "is a".
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];
© 2022 - 2024 — McMap. All rights reserved.