Beyond平君

导航

OC-plist文件写入与读取

在Objective-C开发中,和后续的iOS开发中,经常会碰到需要解析plist文件的。本章简单的来看一下plist文件如何写入与读取.

plist:Property List属性列表,Plist文件通常用于储存用户设置,也可以用于存储捆绑的信息,plist文件的根节点只有array和dictionary两种

下面来看代码:

将数组对象和字典对象写入到plist文件中。

plist文件的写入:

 1 int main(int argc, const char * argv[]) {
 2     @autoreleasepool {
 3         
 4         NSArray *array = [[NSArray alloc] initWithObjects:@"one",@"two",[NSNumber numberWithInt:123],[NSDate date], nil];
 5         //如果传入的目录中没有对应的app.plist文件,则会自动创建一个app.plist文件
 6         //plist文件的根节点(Root)只能是数组(Array)或是字典(Dictionary)
 7         //plist文件中存储的对象只能为7种类型的数据NSArray NSDictionary NSString NSData NSDate NSNumber Boolean
 8         BOOL flag = [array writeToFile:@"/Users/qianfeng/Desktop/lpj/app.plist" atomically:YES];
 9         if (flag) {
10             NSLog(@"array 文件写入成功");
11         }else{
12             NSLog(@"array 文件写入失败");
13         }
14         
15         NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"111",@"ont",@"222",@"two",[NSDate date],@"date",[NSNumber numberWithInteger:1111],@"integer",[NSArray arrayWithObjects:@"000",@"111",@"222", nil],@"array", nil];
16         BOOL flag1 = [dict writeToFile:@"/Users/qianfeng/Desktop/lpj/ff/app.plist" atomically:YES];
17         if (flag1) {
18             NSLog(@"dictionary 文件写入成功");
19         }else{
20             NSLog(@"dictionary 文件写入失败");
21         }
22         
23     }
24     return 0;
25 }

plist文件的读取:

 1 int main(int argc, const char * argv[]) {
 2     @autoreleasepool {
 3         
 4         //将plist文件读取为字典对象
 5         NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/qianfeng/Desktop/day21-OC11_时间类/day21_OC11_plist读取/apple.plist"];
 6         if (dict) {
 7             NSLog(@"dict = %@",dict);
 8         }
 9         else{
10             NSLog(@"dictionary 数据为空");
11         }
12      
13         //将plist文件读取为数组对象
14         NSArray *array = [NSArray arrayWithContentsOfFile:@"/Users/qianfeng/Desktop/day21-OC11_时间类/day21_OC11_plist读取/app.plist"];
15         if (array) {
16             NSLog(@"array = %@",array);
17         }
18         else{
19             NSLog(@"array 数据为空");
20         }
21         
22     }
23     return 0;
24 }

以上便是plist文件的解析,之后的操作就是需要操作数组对象和字典对象了。

posted on 2015-06-26 15:46  Beyond平君  阅读(2147)  评论(0编辑  收藏  举报