1、概述
“归档”意思是持久化存储数据。plist文件是一种XML格式的文件,拓展名为plist。如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,就可以使用writeToFile:atomically:方法直接将对象写到属性列表文件(plist文件)中。特别注意的是plist文件不能存储对象。
IOS常用文件存储方式有:
XML属性列表(plist)归档
Preference(偏好设置)
NSKeyedArchiver归档(NSCoding)
SQLite3
Core Data
2、归档NSDictionary
将一个NSDictionary对象归档到一个plist属性列表中:
首先,将数据封装成字典:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"母鸡" forKey:@"name"];
[dict setObject:@"15013141314" forKey:@"phone"];
[dict setObject:@"27" forKey:@"age"];
其次,获取沙盒中Documents/stu.plist完整路径,根据路径将字典持久化到Documents/stu.plist文件中:
[dict writeToFile:path atomically:YES];//YES代表安全存储
成功写入到Documents目录下后如下图:
用文本编辑器打开,文件内容如下图:
用xcode打开属性文件如下图:
上面是从NSDictionary写入到plist文件,也可以从NSArray写入到plist文件,例如:
// 1.获得沙盒根路径
NSString *home = NSHomeDirectory();
// 2.拼接成document路径
NSString *docPath =
[home stringByAppendingPathComponent:@"Documents"];
// 3.新建数据
NSArray *data = @[@"jack", @10, @"ffdsf"];
//4.拼接成具体文件的路径
NSString *filepath =
[docPath stringByAppendingPathComponent:@"data.plist"];
// 5.写入数据
[data writeToFile:filepath atomically:YES];
3、恢复NSDictionary
读取Documents/stu.plist的内容,实例化NSDictionary
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(@"name:%@", [dict objectForKey:@"name"]);
NSLog(@"phone:%@", [dict objectForKey:@"phone"]);
NSLog(@"age:%@", [dict objectForKey:@"age"]);
打印信息如下:
上面是读取到NSDictionary,对应地,我们也可以读取到NSArray,例如:
// 1.获得沙盒根路径
NSString *home = NSHomeDirectory();
// 2.document路径
NSString *docPath =
[home stringByAppendingPathComponent:@"Documents"];
// 3.文件路径
NSString *filepath =
[docPath stringByAppendingPathComponent:@"data.plist"];
// 4.读取数据
NSArray *data = [NSArray arrayWithContentsOfFile:filepath];
4、NSDictionary的存储和读取过程