iOS plist存储

一、什么是plist文件

Plist文件是Xcode的一种资源包,也可以作为一种存储工具。

二、在项目中创建并使用plist文件

创建plist文件在项目中的好处就是可视化,我们也可以直接操作文件(增删改查)。plist文件的缺点就是作为固态的数据保存,不方便经常改动数据。创建plist文件
选择数据类型

三、对文件进行操作

1、获取文件中的数据
 NSString *string = [[NSBundle mainBundle] pathForResource:@"testPlist" ofType:@"plist"];

 NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:string];

 NSLog(@"%@",dic);   //打印文件中的内容
2、代码创建并读写Plist文件,避免直接在项目中创建plist不方便更改的麻烦。

a、创建存储plist文件的路径。
b、在路径中创建plist文件。
c、将数据写入文件中
d、读取文件

 //创建一个plist文件  testPlist
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistpath = [paths objectAtIndex:0];
    NSLog(@"path = %@",plistpath);
    NSString *filename=[plistpath stringByAppendingPathComponent:@"testPlist.plist"];
    NSFileManager* fm = [NSFileManager defaultManager];
    [fm createFileAtPath:filename contents:nil attributes:nil];

    //写入内容
     NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"test",@"zhangsanfegn",nil];
    [dic writeToFile:filename atomically:YES];

    //读文件
    NSDictionary* dic2 = [NSDictionary dictionaryWithContentsOfFile:filename];
    NSLog(@"dic is:%@",dic2);

文件中数据如下图:
测试结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值