• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Harley
博客园    首页    新随笔    联系   管理    订阅  订阅

动态创建 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 }

 

posted @ 2018-02-24 11:11  Harely  阅读(561)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3