您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

plist 持久化入門:用 writeToFile 存取 Objective-C 物件

編輯:iOS 相關資訊

plist 是什麼?

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:。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved