如何从磁盘加载 plist 文件作为 iOS 上的 NSDictionary?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5354623/
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 load a plist file from disk as a NSDictionary on iOS?
提问by sorin
I want to load the plist file from disk (documents, application cache, ...) not from a resource bundle.
我想从磁盘(文档、应用程序缓存等)而不是从资源包加载 plist 文件。
回答by Lachlan Roche
You can load a plist from any accessible file path with -initWithContentsOfFile:or +dictionaryWithContentsOfFile:
您可以使用-initWithContentsOfFile:或+dictionaryWithContentsOfFile从任何可访问的文件路径加载 plist :
Load a plist from a file, and create the file if it did not exist:
从文件加载 plist,如果文件不存在则创建该文件:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
self.plistFile = [[paths objectAtIndex:0]
stringByAppendingPathComponent:@"example.plist"];
self.plist = [[NSMutableDictionary alloc] initWithContentsOfFile:plistFile];
if (!plist) {
self.plist = [NSMutableDictionary new];
[plist writeToFile:plistFile atomically:YES];
}
回答by Smikey
A little cleaner:
清洁一点:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistName" ofType:@"plist"];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];