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);

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

猜你喜欢

转载自blog.csdn.net/xiaoxiaocode/article/details/79994374
今日推荐