1、创建plist文件。
按command +N快捷键创建,或者File —> New —> New File,选择Mac OS X或者iPhone下的Property List


创建plist文件名为plistdemo。
打开plistdemo文件,在空白出右键,右键选择Add row 添加数据,添加成功一条数据后,在这条数据上右键看到 value Type选择Dictionary。点加号添加这个Dictionary下的数据

添加完key之后在后面添加Value的值,添加手机号和年龄
创建完成之后用source code查看到plist文件是这样的:
-
<?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>
3、读取plist文件的数据
现在文件创建成功了,如何读取呢,实现代码如下:
-
- (void)viewDidLoad
-
{
-
[super viewDidLoad];
-
-
-
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"];
-
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
-
NSLog(@"%@", data);
-
}
打印出来的结果:
-
PlistDemo[6822:f803] {
-
jack = {
-
age = 22;
-
"phone_num" = 13801111111;
-
};
-
tom = {
-
age = 36;
-
"phone_num" = 13901111111;
-
};
-
}
这样就把数据读取出来了。
4、创建和写入plist文件
在开发过程中,有时候需要把程序的一些配置保存下来,或者游戏数据等等。 这时候需要写入Plist数据。
写入的plist文件会生成在对应程序的沙盒目录里。
接着上面读取plist数据的代码,加入了写入数据的代码,
-
<strong>- (void)viewDidLoad
-
{
-
[super viewDidLoad];
-
-
-
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plistdemo" ofType:@"plist"];
-
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
-
NSLog(@"%@", data);
-
-
-
[data setObject:@"add some content" forKey:@"c_key"];
-
-
-
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);
-
-
-
-
}
-
</strong>
在获取到自己手工创建的plistdemo.plist数据后,在这些数据后面加了一项内容,证明输入写入了。
怎么证明添加的内容写入了呢?下面是打印结果:

iOS Plist文件的创建
原文:http://blog.csdn.net/tubiebutu/article/details/46367351