如何在iOS上作为NSDictionary从磁盘加载plist文件?

时间:2011-03-18 16:01:01

标签: ios plist nsdictionary

我想从磁盘(文档,应用程序缓存,...)加载plist文件,而不是从资源包中加载。

2 个答案:

答案 0 :(得分:40)

您可以使用-initWithContentsOfFile:+dictionaryWithContentsOfFile:

从任何可访问的文件路径加载plist

从文件加载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];
}

答案 1 :(得分:24)

一点清洁:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistName" ofType:@"plist"]; 
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];