ios-plist文件讀寫操作 – iPhone手機開發技術文章 iPhone軟體開發教學課程

在做IOS開發時,經常用到到plist文件,  那plist文件是什麼呢? 它全名是:Property List,屬性列表文件,它是一種用來存儲串行化後的對象的文件。屬性列表文件的擴展名為.plist ,因此通常被稱為 plist文件。文件是xml格式的。
 
Plist文件通常用於儲存用戶設置,也可以用於存儲捆綁的信息

我們創建一個項目來學習plist文件的讀寫。

1、創建項目Plistdemo

項目創建之後可以找到項目對應的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文件是這樣的:
 
[cpp] 
<?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> 
    <dict> 
        <key>phone_num</key> 
        <string>13901111111</string> 
        <key>age</key> 
        <string>36</string> 
    </dict> 
</dict> 
</plist> 

 
 
3、讀取plist文件的數據

現在文件創建成功瞭,如何讀取呢,實現代碼如下:
[cpp]
– (void)viewDidLoad 

    [super viewDidLoad]; 
    //讀取plist 
 
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"]; 
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath]; 
    NSLog(@"%@", data);//直接打印數據。 

打印出來的結果:
 
[cpp]
PlistDemo[6822:f803] { 
    jack =     { 
        age = 22; 
        "phone_num" = 13801111111; 
    }; 
    tom =     { 
        age = 36; 
        "phone_num" = 13901111111; 
    }; 

 
這樣就把數據讀取出來瞭。
 

4、創建和寫入plist文件
在開發過程中,有時候需要把程序的一些配置保存下來,或者遊戲數據等等。 這時候需要寫入Plist數據。
寫入的plist文件會生成在對應程序的沙盒目錄裡。
接著上面讀取plist數據的代碼,加入瞭寫入數據的代碼,
 
[cpp]
<strong>- (void)viewDidLoad 

    [super viewDidLoad]; 
    //讀取plist 
 
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"]; 
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath]; 
    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> 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *