读取plist文件
来源:互联网 发布:手机热血传奇挂机软件 编辑:程序博客网 时间:2024/05/01 10:35
这个 从别人那拿来的挺好使 呵呵
在Xcode中建立一个iOS项目后,会自己产生一个.plist文件,点击时会看见它显示的是类似于excel表格:
但是,如果打开方式选择SourceCode,你会看见它其实是一个xml文件。
我们会做一个小例子,在这个例子中我们自己建立一个plist文件并填入数据,然后运行时读取这个plist文件,并将数据填写在界面上。
首先要知道读取plist文件的方法,一般来说,使用代码
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"listFileName" ofType:@"plist"];NSArray *array = [[NSArray alloc] initWithContentsOfFile:plistPath];NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
已经足够了,此时可以使用NSLog例程查看array和dictionary的内容。不过,有时候受plist文件内容的限制,array内容可能为空。
其实,用dictionary就已经足够了,在下面的例子里我们也只用dictionary。
1、运行Xcode4.2,新建一个Single ViewApplication,名称为ReadPlistFile,其他设置如下图:
2、新建我们自己的plist文件:
File —> New —> New File,选择Mac OSX下的Property List
文件名为 customInfo,Group选择Supporting Files。
3、单击新建的customInfo.plist,我们添加数据,如下图:
注意,Type一项的类型,选择的是Dictionary,以SourceCode打开,显示如下:
<?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方法中的[superviewDidLoad]之后添加如下代码:
//首先读取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、运行,查看效果:
- 读取plist文件
- IOS读取.plist文件
- NSArray 读取plist文件
- 读取plist文件
- OC读取plist文件
- 读取plist文件
- plist文件读取
- ios读取plist文件
- iOS -读取plist文件
- 读取plist文件
- plist文件读取
- cocos2d读取plist文件
- IOS 读取Json文件、读取plist文件
- 读取和写入plist文件
- 创建与读取 plist 文件
- 读取和写入plist文件
- IOS读取plist资源文件
- plist文件读取并动画
- 新闻登陆系统
- iOS学习之UISwitch控件两种使用方…
- ios 隐藏键盘
- 用代码改变按钮字体的颜色
- 动态添加按钮
- 读取plist文件
- UITableViewController 的分组
- 使用Tool Bar切换视图
- web服务器的开启和php模块的开启
- Maven + CRUD + Spring + Hibernate + MySQL/Sql Server 2008
- 关于mysql的安装和在终端上简单的…
- 算法
- 关于mysql的安装和在终端上简单的…
- 图片框角处理