开发者

How do I use the writeToFile method on an NSMutableDictionary?

I would like to use a method (writeToFi开发者_如何学Cle) 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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜