iOS 归档解档以及删除
最近公司需求中新添加类似于微信朋友圈,保存草稿功能,不多BB,上代码:
// 写入
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString*documentFilePath = paths.firstObject ;
//路径名称
NSString *filePath = [documentFilePath stringByAppendingPathComponent:@"XXX"];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver*archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; //将数据区连接到NSKeyedArchiver对象
//需要存储的key and value
[archiver encodeObject:aTextString forKey:@"xxxx"];
[archiver encodeObject:infoArr forKey:@"xxxxx"];
[archiver finishEncoding];
//写入
[data writeToFile:filePathatomically:YES];
//取出
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString*documentFilePath = paths.firstObject ;
NSString *filePath = [documentFilePath stringByAppendingPathComponent:@"xxxx"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSAttributedString*textStr = [unarchiver decodeObjectForKey:@"xxxx"];
self.aTextString= textStr;
self.textString= (NSMutableString*)textStr;
self.infoArray= [unarchiver decodeObjectForKey:@"xxxx"];
self.infoArrayCopy= [unarchiver decodeObjectForKey:@"xxxx"];
[unarchiver finishDecoding];
//置空
NSMutableArray *array = [NSMutableArray array];
NSAttributedString *aTextStr = [[NSAttributedString alloc]initWithString:@""];
//重新走一遍归档
xxxxxxx
//用户退出时删除
NSFileManager *defaultManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString*documentFilePath = paths.firstObject ;
//找到路径
NSString *filePath = [documentFilePath stringByAppendingPathComponent:@"xxxx"];
//判断是否包含 有直接删除
if([defaultManager isDeletableFileAtPath:filePath]) {
[defaultManager removeItemAtPath:filePath error:nil];
}