开发者

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

I want to load the plist file from disk (documents, application cache, ...) not from a resource bundle.开发者_Python百科


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


A little cleaner:

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


It's always good to have a Swift version. It load a plist from the bundle.

if let plistPath = Bundle.main.path(forResource: "plistName", ofType: "plist") {
    let dict = NSDictionary(contentsOfFile: plistPath)
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜