How do I load a plist file from disk as a NSDictionary on iOS?

感情迁移 提交于 2019-11-26 21:31:46

问题


I want to load the plist file from disk (documents, application cache, ...) not from a resource bundle.


回答1:


You can load a plist from any accessible file path with -initWithContentsOfFile: or +dictionaryWithContentsOfFile:

Load a plist from a file, and create the file if it did not exist:

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];
}



回答2:


A little cleaner:

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


来源:https://stackoverflow.com/questions/5354623/how-do-i-load-a-plist-file-from-disk-as-a-nsdictionary-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!