iOS應用中存儲用戶設置的plist文件的創(chuàng)建與讀寫教程
在做iOS開發(fā)時,經(jīng)常用到到plist文件, 那plist文件是什么呢? 它全名是:Property List,屬性列表文件,它是一種用來存儲串行化后的對象的文件。屬性列表文件的擴展名為.plist ,因此通常被稱為 plist文件。文件是xml格式的。
Plist文件通常用于儲存用戶設置,也可以用于存儲捆綁的信息
我們創(chuàng)建一個項目來學習plist文件的讀寫。
1、創(chuàng)建項目Plistdemo
項目創(chuàng)建之后可以找到項目對應的plist文件,打開如下圖所示:

在編輯器中顯示類似與表格的形式,可以在plist上右鍵,用源碼方式打開,就能看到plist文件的xml格式了。
2、創(chuàng)建plist文件。
按command +N快捷鍵創(chuàng)建,或者File —> New —> New File,選擇Mac OS X下的Property List

文件名為 customInfo,Group選擇Supporting Files。
3、單擊新建的customInfo.plist,我們添加數(shù)據(jù),如下圖:

注意,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中的數(shù)據(jù)
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、運行,查看效果:

相關文章
iOS App開發(fā)中UIViewController類的使用教程
UIViewController是iOS中控制視圖的關鍵所在,這里我們將針對UIViewController的聲明周期與主要屬性和方法,來總結iOS App開發(fā)中UIViewController類的使用教程2016-07-07
iOS NSNotificationCenter通知中心使用小結
IOS中經(jīng)常會使用到NSNotification和delegate來進行一些類之間的消息傳遞,這篇文章主要介紹了iOS NSNotificationCenter使用小結,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
iOS利用NSMutableAttributedString實現(xiàn)富文本的方法小結
這篇文章主要給大家介紹了關于iOS利用NSMutableAttributedString如何實現(xiàn)富文本的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-05-05
IOS數(shù)字鍵盤左下角添加完成按鈕的實現(xiàn)方法
這篇文章主要介紹了IOS數(shù)字鍵盤左下角添加完成按鈕的實現(xiàn)方法的相關資料,希望通過本文能實現(xiàn)類似這樣的功能,需要的朋友可以參考下2017-08-08

