您的位置:首页 > 移动开发 > IOS开发

iOS05 PropertyList,即属性列表文件

2015-12-16 10:03 411 查看
plist,全名PropertyList,即属性列表文件,它是一种用来存储串行化后的对 象的文件。这种文件,在ios开发过程中经常被用到。这种属性列表文件的扩展名为.plist,因此通常被叫做plist文件。文件是xml格式的。 Plist文件是以key-value的形式来存储数据。既可以用来存储用户设置,也可以用来存储一些需要经常用到而不经常改动的信息。
在对plist文件的操作有创建,删除,写入和读取。这四种操作中,写入和读取是比较常用的操作。
下面我对这四种操作进行一一的陈述。
首先,是怎么去创建plist文件。Plist文件的创建既可以通过在程序中通过新建文件的方式来创建,也可以通过在程序中用代码的形式来创建文件。
第一种就是通过新建文件,在弹出的窗口中选择ios项目下的Resource中的 Property List来进行plist文件的创建。然后点击TestPlistDemo.plist文件,出现一个Root行,点击Root这一行,然后通过点击右键 ->Add Row或者点击Root后面的加号来增加一行。这一行中包含三个属性,key、type、value。其中key是字段属性,type是字段类 型,value是字段对应的值。而Type又包含7中类型,其中两种是Array和Dictionary,这两种是数组的形式,在它们下面还可以包含许多 key-value。
而另外5种是Boolean,data,string,date,number。这5种类型的数据都是被array和dictionary所要包含的数据。
通过代码来创建plist文件,代码如下:
//建立文件管理
NSFileManager *fm = [NSFileManager defaultManager];
//找到Documents文件所在的路径
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUSErDomainMask, YES);
//取得第一个Documents文件夹的路径
NSString *filePath = [path objectAtIndex:0];
//把TestPlist文件加入
NSString *plistPath = [filePath stringByAppendingPathComponent:@"test.plist"];
//开始创建文件
[fm createFileAtPath:plistPath contents:nil attributes:nil];
//删除文件
[fm removeItemAtPath:plistPath error:nil];
在写入数据之前,需要把要写入的数据先写入一个字典中,创建一个dictionary:
//创建一个字典
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"zhangsan",@"1",@"lisi",@"2", nil];
//把数据写入plist文件
[dic writeToFile:plistPath atomically:YES];
读取plist中的数据,形式如下:
//读取plist文件,首先需要把plist文件读取到字典中
NSDictionary *dic2 = [NSDictionary dictionaryWithContentsOfFile:plistPath];
//打印数据
NSLog(@"key1 is %@",[dic2 valueForKey:@"1"]);
NSLog(@"dic is %@",dic2); http://www.linuxidc.com 关于plist中的array读写,代码如下:
//把TestPlist文件加入
NSString *plistPaths = [filePath stringByAppendingPathComponent:@"tests.plist"];
//开始创建文件
[fm createFileAtPath:plistPaths contents:nil attributes:nil];
//创建一个数组
NSArray *arr = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4", nil];
//写入
[arr writeToFile:plistPaths atomically:YES];
//读取
NSArray *arr1 = [NSArray arrayWithContentsOfFile:plistPaths];
//打印
NSLog(@"arr1is %@",arr1);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: