15

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

sorin
  • 161,544
  • 178
  • 535
  • 806

3 Answers3

41

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];
}
Lachlan Roche
  • 25,678
  • 5
  • 79
  • 77
  • 1
    Note that the Plist's root object must be a dictionary. If the root object is an array, you should use [[NSArray alloc] initWithContentsOfFile:plistFile]; – Ash Jan 02 '14 at 17:36
28

A little cleaner:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistName" ofType:@"plist"]; 
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; 
Smikey
  • 8,106
  • 3
  • 46
  • 74
1

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)
}
Pau Ballada
  • 1,491
  • 14
  • 13