动态创建 Plist 文件

简介

Property List,属性列表文件,它是一种用来存储串行化后的对象的文件。属性列表文件的扩展名为.plist ,因此通常被称为 plist文件,文件是xml格式的。

 

写入plist文件

在开发过程中,有时候需要把程序的一些配置保存下来,或者游戏数据等等。 这时候需要写入Plist数据。写入的plist文件会生成在对应程序的沙盒目录里。

 1 -(void)triggerStorage
 2 {
 3 //    displayLabel.text = textInput.text;
 4     
 5     NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
 6     NSString *path=[paths    objectAtIndex:0];
 7     NSString *filename=[path stringByAppendingPathComponent:@"test.plist"];   //获取路径
 8     
 9     NSDictionary* dic2 = [NSDictionary dictionaryWithContentsOfFile:filename];  //读取数据
10     NSLog(@"dic2 is:%@",dic2);
11     
12     //创建一个dic,写到plist文件里
13     NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:@"displayLabel.text",@"IP",nil]; //写入数据
14 //    或者 [dic setObject:@"add some content" forKey:@"c_key"];
15     [dic writeToFile:filename atomically:YES];
16     
17 }

 

 

读取文件

 1 - (void)readData {
 2     NSMutableArray *resultData;
 3 //    获取应用程序沙盒的Documents目录
 4     NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
 5     NSString *path=[paths objectAtIndex:0];
 6     NSLog(@"path = %@",path);
 7 //    得到完整的文件名
 8     NSString *filename=[path stringByAppendingPathComponent:@"test.plist"];
 9     
10     //读文件
11     NSDictionary* dic2 = [NSDictionary dictionaryWithContentsOfFile:filename];
12     NSLog(@"dic is:%@",dic2);
13     if(dic2 == nil)
14     {
15         //1. 创建一个plist文件
16         NSFileManager* fm = [NSFileManager defaultManager];
17         [fm createFileAtPath:filename contents:nil attributes:nil];
18     }
19     else
20     {
21         resultData=[dic2 objectForKey:@"IP"];
22         if([dic2 count] > 0)
23         {
24 //            displayLabel.text = resultData;
25             NSLog(@"读取的值是:%@", resultData);
26         }
27         else
28         {
29 //            displayLabel.text = @" ";
30             NSLog(@"没有读取到任何值!");
31         }
32     }
33 }

 

转载于:https://www.cnblogs.com/EchoHG/p/8464743.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值