2011-03-18 134 views

回答

39

您可以從任何可訪問文件路徑與-initWithContentsOfFile:+dictionaryWithContentsOfFile:

加載一個的plist從文件加載的plist,如果不存在,創建該文件:

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

請注意,Plist的根對象必須是字典。如果根對象是一個數組,你應該使用[[NSArray alloc] initWithContentsOfFile:plistFile]; – Ash 2014-01-02 17:36:36

23

乾淨了一點:

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

取決於目錄,documentdirectory!=資源路徑 – M0rph3v5 2015-01-12 10:28:50