iOS應用中儲存使用者佈建的plist檔案的建立與讀寫教程_IOS

來源:互聯網
上載者:User

    在做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

檔案名稱為 customInfo,Group選擇Supporting Files。

3、單擊建立的customInfo.plist,我們添加資料,如下圖:

注意,Type一項的類型,選擇的是Dictionary,以Source Code開啟,顯示如下:

<?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>Student</key> <dict> <key>Name</key> <string>Yang</string> <key>Sex</key> <string>Male</string> <key>Num</key> <string>SX_010</string> </dict> <key>Mentor</key> <dict> <key>Name</key> <string>Gu</string> <key>Sex</key> <string>Male</string> </dict></dict></plist>

4、為視圖添加控制項:
單擊BIDViewController.xib,開啟IB,拖幾個控制項上去,並設定好布局,如下圖:

上圖中所有的控制項都是Label,並設定了字型大小。

5、接下來就是映射唄,把五個灰色的Label都映射到BIDViewController.h檔案中,類型都是OutLet,名稱依次是stuName,stuSex,stuNum,mtName,mtSex。

6、單擊BIDViewController.m,在viewDidLoad方法中的[super viewDidLoad]之後添加如下代碼:

複製代碼 代碼如下:

//首先讀取studentInfo.plist中的資料
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"customInfo" ofType:@"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
   
//將學生資訊填入視圖
NSDictionary *tmpInfo = [dictionary objectForKey: @"Student"];
self.stuName.text = [NSString stringWithFormat:@"%@", [tmpInfo objectForKey: @"Name"]];
self.stuSex.text = [NSString stringWithFormat:@"%@", [tmpInfo objectForKey: @"Sex"]];
self.stuNum.text = [NSString stringWithFormat:@"%@", [tmpInfo objectForKey: @"Num"]];
   
//將導師資訊寫入視圖
tmpInfo = [dictionary objectForKey: @"Mentor"];
self.mtName.text = [NSString stringWithFormat:@"%@", [tmpInfo objectForKey: @"Name"]];
self.mtSex.text = [NSString stringWithFormat:@"%@", [tmpInfo objectForKey: @"Sex"]];

7、運行,查看效果:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.