14

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

sorin
  • 149,293
  • 163
  • 498
  • 754

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,340
  • 5
  • 80
  • 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
27

A little cleaner:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistName" ofType:@"plist"]; 
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; 
Smikey
  • 7,826
  • 3
  • 44
  • 74
0

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,245
  • 12
  • 11