1. 程式人生 > >iOS 建立.寫入.讀取plist檔案

iOS 建立.寫入.讀取plist檔案

plist,全名PropertyList,即屬性列表檔案,它是一種用來儲存序列化後的物件的檔案。這種檔案,在iOS開發過程中經常被用到。這種屬性列表檔案的副檔名為.plist,因此通常被叫做plist檔案。檔案是xml格式的。Plist檔案是以key-value的形式來儲存資料。既可以用來儲存使用者設定,也可以用來儲存一些需要經常用到而不經常改動的資訊。

在對plist檔案的操作有建立,刪除,寫入和讀取。這四種操作中,寫入和讀取是比較常用的操作。

下面我對這四種操作進行一一的陳述。

首先,是怎麼去建立plist檔案。Plist檔案的建立既可以通過在程式中通過新建檔案的方式來建立,也可以通過在程式中用程式碼的形式來建立檔案。

第一種就是通過新建檔案,在彈出的視窗中選擇ios專案下的Resource中的Property List來進行plist檔案的建立。然後點選TestPlistDemo.plist檔案,出現一個Root行,點選Root這一行,然後通過點選右鍵->Add Row或者點選Root後面的加號來增加一行。這一行中包含三個屬性,key、type、value。其中key是欄位屬性,type是欄位型別,value是欄位對應的值。而Type又包含7中型別,其中兩種是Array和Dictionary,這兩種是陣列的形式,在它們下面還可以包含許多key-value。

而另外5種是Boolean,data,string,date,number。這5種類型的資料都是被array和dictionary所要包含的資料。

通過程式碼來建立plist檔案,程式碼如下:

//建立檔案管理

    NSFileManager *fm = [NSFileManager defaultManager];

    //找到Documents檔案所在的路徑

    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    //取得第一個Documents資料夾的路徑

    NSString *filePath = [path objectAtIndex:0];

    //把TestPlist檔案加入

    NSString *plistPath = [filePath stringByAppendingPathComponent:@"test.plist"];

    //開始建立檔案

[fm createFileAtPath:plistPath contents:nil attributes:nil];

//刪除檔案

[fm removeItemAtPath:plistPath error:nil];

在寫入資料之前,需要把要寫入的資料先寫入一個字典中,建立一個dictionary:

    //建立一個字典

    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"zhangsan",@"1",@"lisi",@"2", nil];

    //把資料寫入plist檔案

[dic writeToFile:plistPath atomically:YES];

讀取plist中的資料,形式如下:

    //讀取plist檔案,首先需要把plist檔案讀取到字典中

    NSDictionary *dic2 = [NSDictionary dictionaryWithContentsOfFile:plistPath];

    //列印資料

    NSLog(@"key1 is %@",[dic2 valueForKey:@"1"]);

NSLog(@"dic is %@",dic2);

http://www.linuxidc.com

關於plist中的array讀寫,程式碼如下:

//把TestPlist檔案加入

    NSString *plistPaths = [filePath stringByAppendingPathComponent:@"tests.plist"];

    //開始建立檔案

    [fm createFileAtPath:plistPaths contents:nil attributes:nil];

    //建立一個數組

    NSArray *arr = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4", nil];

    //寫入

    [arr writeToFile:plistPaths atomically:YES];

    //讀取

    NSArray *arr1 = [NSArray arrayWithContentsOfFile:plistPaths];

    //列印

    NSLog(@"arr1is %@",arr1);