做 iOS 開發時,plist 幾乎是每個專案都會碰到的東西。它全名是 Property List(屬性列表),是一種用來保存序列化後物件的檔案格式,副檔名為 .plist,內容採用 XML 結構。最常見的用途是存放使用者設定,以及應用程式捆綁(bundle)的相關資訊。
以下用一個名為 PlistDemo 的小專案,把「建立、讀取、寫入」三件事走一遍。
建立專案 PlistDemo 之後,可以在專案結構中找到系統自動產生的 plist 檔案。以編輯器打開時,它以表格形式呈現;在檔案上按右鍵選擇「以源碼方式開啟」,就能看到背後的 XML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"https://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>jack</key>
<dict>
<key>phone_num</key>
<string>13801111111</string>
<key>age</key>
<string>22</string>
</dict>
<key>tom</key>
<dict>
<key>phone_num</key>
<string>13901111111</string>
<key>age</key>
<string>36</string>
</dict>
</dict>
</plist>從結構不難看出,plist 本質上就是巢狀的字典(dict)與陣列(array),這也是它能直接對應到 NSDictionary 與 NSArray 的原因。
用 Command + N,或 File → New → New File,選擇 Mac OS X 底下的 Property List,命名為 plistdemo。
建立完成後,在空白處按右鍵選擇 Add Row 新增一筆資料;接著在這筆資料上按右鍵,把 Value Type 改為 Dictionary,然後點加號往這個 Dictionary 裡補上 key 與 value,例如手機號碼與年齡。用 Source Code 檢視,就會得到上面那段 XML 的樣子。
- (void)viewDidLoad
{
[super viewDidLoad];
// 讀取 plist
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo"
ofType:@"plist"];
NSMutableDictionary *data =
[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSLog(@"%@", data); // 直接印出來看看
}執行後的輸出結果:
PlistDemo[6822:f803] {
jack = {
age = 22;
"phone_num" = 13801111111;
};
tom = {
age = 36;
"phone_num" = 13901111111;
};
}資料就這樣被讀進來了。這裡有個細節值得注意:initWithContentsOfFile: 讀進來的是不可變的 NSDictionary 語意,因此若要修改內容,記得用 NSMutableDictionary 承接。
開發過程中常需要把程式的組態或遊戲存檔保存下來,這時就要寫入 plist。寫入的檔案會落在 App 的沙盒目錄裡,而不是原本的 bundle 中——bundle 是唯讀的,這點非常重要。
- (void)viewDidLoad
{
[super viewDidLoad];
// 1. 先讀取 bundle 內的 plist
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo"
ofType:@"plist"];
NSMutableDictionary *data =
[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSLog(@"%@", data);
// 2. 新增一筆內容
[data setObject:@"add some content" forKey:@"c_key"];
// 3. 取得 App 沙盒的 Documents 目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *plistPath1 = [paths objectAtIndex:0];
// 4. 拼出完整的檔案路徑
NSString *filename = [plistPath1 stringByAppendingPathComponent:@"test.plist"];
// 5. 寫入
[data writeToFile:filename atomically:YES];
// 6. 怎麼證明真的寫進去了?讀回來看看
NSMutableDictionary *data1 =
[[NSMutableDictionary alloc] initWithContentsOfFile:filename];
NSLog(@"%@", data1);
}這段程式碼的重點在於第 3 步:一定要先取得沙盒內可寫的目錄(Documents 或 Library),再把資料寫進去,而不是硬寫回 bundle。最後再讀一次寫入的檔案,是最簡單也最有效的驗證方式。
至於 plist 的適用界線也要心裡有數:它適合存放結構簡單、資料量不大的設定值。若資料量大或需要查詢,就該改用 Core Data 或 SQLite 了。