iOS開發:資料存放區之plist檔案操作

來源:互聯網
上載者:User

標籤:http   io   ar   os   sp   for   檔案   資料   on   

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

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

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

首先,是怎麼去建立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);

 

iOS開發:資料存放區之plist檔案操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.