plist 本質上是 XML 格式的屬性列表檔案,副檔名通常為 .plist。在 iOS 與 macOS 開發中,它常被用來保存輕量級設定或結構化資料。
若資料是 NSString、NSDictionary、NSArray、NSData、NSNumber 等 property list 支援的型別,就能透過 writeToFile:atomically: 直接存檔。
NSString *home = NSHomeDirectory(); NSString *docPath = [home stringByAppendingPathComponent:@"Documents"]; NSArray *data = @[@"jack", @10, @"ffdsf"]; NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"]; [data writeToFile:filepath atomically:YES];
atomically 設為 YES 時,系統會先寫入暫存檔,完成後再取代目標檔案,可降低寫入中斷造成檔案損壞的風險。
NSString *home = NSHomeDirectory(); NSString *docPath = [home stringByAppendingPathComponent:@"Documents"]; NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"]; NSArray *data = [NSArray arrayWithContentsOfFile:filepath]; NSLog(@"%@", data);
使用 arrayWithContentsOfFile: 即可把 plist 還原成陣列;若檔案是字典,也可使用 dictionaryWithContentsOfFile:。