ios 如何在 NSMutableDictionary 上使用 writeToFile 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7478688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use the writeToFile method on an NSMutableDictionary?
提问by Steve
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 对象使用仅适用于 NSDictionary的方法(writeToFile)。那么,如何将这个 NSMutableDictionary 对象转换为 NSDictionary?
回答by Daryl Teo
NSMutableDictionary inherits from NSDictionary. So, writeToFile should be available to both classes.
NSMutableDictionary 继承自 NSDictionary。因此,两个类都应该可以使用 writeToFile。
回答by Yoga
For those coming here genuinely looking for conversion from NSMutableDictionary to NSDictionary :
对于那些真正想要从 NSMutableDictionary 转换为 NSDictionary 的人:
NSMutableDictionary *mutableDict = [[[NSDictionary alloc] initWithObjectsAndKeys:
@"value", @"key"] mutableCopy];
NSDictionary *dict = [NSDictionary dictionaryWithDictionary:mutableDict]; //there you have it
回答by Jeremy Flores
NSMutableDictionary is a subclass of NSDictionary, so the writeToFile method should be available for your object without having to do any casting or conversions.
NSMutableDictionary 是 NSDictionary 的子类,因此 writeToFile 方法应该可用于您的对象,而无需进行任何强制转换或转换。
回答by adpalumbo
As already discussed here:
正如这里已经讨论过的:
How to save a NSMutableDictionary into a file in documents?
如何将 NSMutableDictionary 保存到文档中的文件中?
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
.
但是,如果您真的想,只需使用copy
您NSMutableDictionary
的dictionaryWithDictionary:
方法或 上的方法NSDictionary
。两者都提供NSDictionary
来自NSMutableDictionary
.
回答by zaph
A NSMutableDictionary isa NSDictionary since it is a subclass. Typically the relationship of a subclass to it's superclass is called: "is a".
NSMutableDictionary是NSDictionary,因为它是一个子类。通常,子类与其超类的关系称为:“是一个”。
回答by Daniel Galasko
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.
为了解决实际的问题标题而不是内容(因为我搜索了这个 Q),你实际上可以依靠copyWithZone:
一个不可变的字典。
NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] init];
mutableDict[@"key"] = @"value";
NSDictionary *immutableDict = [mutableDict copy];