在做iOS開發時,經常用到到plist檔案, 那plist檔案是什麼呢? 它全名是:Property List,屬性清單檔案,它是一種用來存儲串行化後的對象的檔案。屬性清單檔案的擴充名為.plist ,是以通常被稱為 plist檔案。檔案是xml格式的。
Plist檔案通常用于儲存使用者設定,也可以用于存儲捆綁的資訊
我們建立一個項目來學習plist檔案的讀寫。
1、建立項目Plistdemo
如果要通過代碼建立的話,則需要通過[NSBundle mainBundle]來獲得目前工程的目錄,然後還可以通過pathForResource來獲得項目中資源的路徑
項目建立之後可以找到項目對應的plist檔案,打開如下圖所示:

在編輯器中顯示類似與表格的形式,可以在plist上右鍵,用源碼方式打開,就能看到plist檔案的xml格式了。
2、建立plist檔案。
按command +N快捷鍵建立,或者File —> New —> New File,選擇Mac OS X下的Property List
建立plist檔案名為plistdemo。
打開plistdemo檔案,在空白出右鍵,右鍵選擇Add row 添加資料,添加成功一條資料後,在這條資料上右鍵看到 value Type選擇Dictionary。點加号添加這個Dictionary下的資料
添加完key之後在後面添加Value的值,添加手機号和年齡
建立完成之後用source code檢視到plist檔案是這樣的:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://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>
<string>13901111111</string>
<string>36</string>
</dict>
</plist>
3、讀取plist檔案的資料
現在檔案建立成功了,如何讀取呢,實作代碼如下:
- (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;
這樣就把資料讀取出來了。
4、建立和寫入plist檔案
在開發過程中,有時候需要把程式的一些配置儲存下來,或者遊戲資料等等。 這時候需要寫入Plist資料。
寫入的plist檔案會生成在對應程式的沙盒目錄裡。
接着上面讀取plist資料的代碼,加入了寫入資料的代碼,
<strong>- (void)viewDidLoad
NSLog(@"%@", data);
//添加一項内容
[data setObject:@"add some content" forKey:@"c_key"];
//擷取應用程式沙盒的Documents目錄
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *plistPath1 = [paths objectAtIndex:0];
//得到完整的檔案名
NSString *filename=[plistPath1 stringByAppendingPathComponent:@"test.plist"];
//輸入寫入
[data writeToFile:filename atomically:YES];
//那怎麼證明我的資料寫入了呢?讀出來看看
NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
NSLog(@"%@", data1);
// Do any additional setup after loading the view, typically from a nib.
</strong>
在擷取到自己手工建立的plistdemo.plist資料後,在這些資料後面加了一項内容,證明輸入寫入了。
怎麼證明添加的内容寫入了呢?下面是列印結果: