在作iOS开发时,常常用到到plist文件, 那plist文件是什么呢? 它全名是:Property List,属性列表文件,它是一种用来存储串行化后的对象的文件。属性列表文件的扩展名为.plist ,所以一般被称为 plist文件。文件是xml格式的。
app
Plist文件一般用于储存用户设置,也能够用于存储捆绑的信息编辑器
咱们建立一个项目来学习plist文件的读写。学习
一、建立项目Plistdemoatom
项目建立以后能够找到项目对应的plist文件,打开以下图所示:spa
在编辑器中显示相似与表格的形式,能够在plist上右键,用源码方式打开,就能看到plist文件的xml格式了。.net
二、建立plist文件。code
按command +N快捷键建立,或者File —> New —> New File,选择Mac OS X下的Property Listxml
建立plist文件名为plistdemo。对象
打开plistdemo文件,在空白出右键,右键选择Add row 添加数据,添加成功一条数据后,在这条数据上右键看到 value Type选择Dictionary。点加号添加这个Dictionary下的数据blog
添加完key以后在后面添加Value的值,添加手机号和年龄
建立完成以后用source code查看到plist文件是这样的:
[cpp] view plaincopy
<?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>jack</key>
<dict>
<key>phone_num</key>
<string>13801111111</string>
<key>age</key>
<string>22</string>
</dict>
<key>tom</key>
<dict>
<key>phone_num</key>
<string>13901111111</string>
<key>age</key>
<string>36</string>
</dict>
</dict>
</plist>
三、读取plist文件的数据
如今文件建立成功了,如何读取呢,实现代码以下:
[cpp] view plaincopy
- (void)viewDidLoad
{
[super viewDidLoad];
//读取plist
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSLog(@"%@", data);//直接打印数据。
}
打印出来的结果:
[cpp] view plaincopy
PlistDemo[6822:f803] {
jack = {
age = 22;
"phone_num" = 13801111111;
};
tom = {
age = 36;
"phone_num" = 13901111111;
};
}
这样就把数据读取出来了。
四、建立和写入plist文件
在开发过程当中,有时候须要把程序的一些配置保存下来,或者游戏数据等等。 这时候须要写入Plist数据。
写入的plist文件会生成在对应程序的沙盒目录里。
接着上面读取plist数据的代码,加入了写入数据的代码,
[cpp] view plaincopy
<strong>- (void)viewDidLoad
{
[super viewDidLoad];
//读取plist
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSLog(@"%@", data);
//添加一项内容
[data setObject:@"add some content" forKey:@"c_key"];
//获取应用程序沙盒的Documents目录
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *plistPath1 = [paths objectAtIndex:0];
//获得完整的文件名
NSString *filename=[plistPath1 stringByAppendingPathComponent:@"test.plist"];
//输入写入
[data writeToFile:filename atomically:YES];
//那怎么证实个人数据写入了呢?读出来看看
NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
NSLog(@"%@", data1);
// Do any additional setup after loading the view, typically from a nib.
}
</strong>
在获取到本身手工建立的plistdemo.plist数据后,在这些数据后面加了一项内容,证实输入写入了。
怎么证实添加的内容写入了呢?下面是打印结果: