Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 259
sorin Avatar asked Mar 18 '11 16:03

sorin


2 Answers

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];
}
like image 199
Lachlan Roche Avatar answered Oct 11 '22 13:10

Lachlan Roche


A little cleaner:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistName" ofType:@"plist"]; 
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; 
like image 40
Smikey Avatar answered Oct 11 '22 13:10

Smikey