欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS应用中存储用户设置的plist文件的创建与读写教程

程序员文章站 2023-11-28 21:59:58
    在做ios开发时,经常用到到plist文件,  那plist文件是什么呢? 它全名是:property list,属性列表文...

    在做ios开发时,经常用到到plist文件,  那plist文件是什么呢? 它全名是:property list,属性列表文件,它是一种用来存储串行化后的对象的文件。属性列表文件的扩展名为.plist ,因此通常被称为 plist文件。文件是xml格式的。
plist文件通常用于储存用户设置,也可以用于存储捆绑的信息

我们创建一个项目来学习plist文件的读写。

1、创建项目plistdemo
项目创建之后可以找到项目对应的plist文件,打开如下图所示:

iOS应用中存储用户设置的plist文件的创建与读写教程

在编辑器中显示类似与表格的形式,可以在plist上右键,用源码方式打开,就能看到plist文件的xml格式了。

2、创建plist文件。
按command +n快捷键创建,或者file —> new —> new file,选择mac os x下的property list

iOS应用中存储用户设置的plist文件的创建与读写教程

文件名为 custominfo,group选择supporting files。

3、单击新建的custominfo.plist,我们添加数据,如下图:

iOS应用中存储用户设置的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,拖几个控件上去,并设置好布局,如下图:

iOS应用中存储用户设置的plist文件的创建与读写教程

上图中所有的控件都是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、运行,查看效果:

iOS应用中存储用户设置的plist文件的创建与读写教程

上一篇: iOS编写下拉刷新控件

下一篇: