归档就是将数据整理到外部文件(XML,plist,text等)
在oc中支持归档的数据类型包括NSData,NSNumber,NSString,NSArray,NSDictionary
代码:
+ (NSString *)getDocumentPath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
NSString *filePath = [self getDocumentPath];
NSMutableArray *arry1 = [NSMutableArray arrayWithObjects:per,new, nil];
NSString *arrPath = [filePath stringByAppendingPathComponent:@"string"];
//归档
[arry1 writeToFile:arrPath atomically:YES];
atomically:这个参数意思是如果为YES则保证文件的写入原子性,就是说会先创建一个临时文件,直到文件内容写入成功再导入到目标文件里.
如果为NO,则直接写入目标文件里.
//读取数据
NSArray *arr = [NSArray arrayWithContentsOfFile:arrPath];
除了上述归档,我们还可以用NSKeyedArchiver方式来进行归档,和NSKeyedUnarchiver方式来进行反归档,
代码:
NSString *arrPath = [filePath stringByAppendingPathComponent:@"arr.archiver"];
//归档
[NSKeyedArchiver archiveRootObject:arry1 toFile:arrPath];
//反归档
NSArray *ARR =[NSKeyedUnarchiver unarchiveObjectWithFile:arrPath];