概念:归档是把对象写入文件保存在硬盘中,当再次重新打开程序时,可以还原这些对象。
归档主要用到 NSKeyedArchiver 、 NSKeyedUnarchiver 两个类
NSKeyedArchiver 中使用archiveRootObject:toFile: 或者 archivedDataWithRootObject: 来归档类。
NSKeyedUnarchiver 中使用narchiveObjectWithFile: 或者 unarchiveObjectWithData: 来反归档类。
归档系统自带的类
因NSString、NSArray、NSData、NSDictionary 都实现了NSCoding协议,可直接通过调用writeToFile归档。
归档自定义的类
首先实现NSCoding协议,重写encodeWithCode方法和initWithCode方法,然后通过NSKeyedArchiver转换为NSData,再通过NSData的writeToFile方法写入到文件,
或者将转换后的NSData放入到NSArray或NSDictionary中调用writeToFile写入到文件便可实现包装了自定义类型的数据和字典的归档。
//自定义类与系统类组合一起
采用encodeObject方式归档
采用decodeObjectForKey方式反归档
文件的创建
文件的写入
文件的读取
文件的移动
文件的删除
归档主要用到 NSKeyedArchiver 、 NSKeyedUnarchiver 两个类
NSKeyedArchiver 中使用archiveRootObject:toFile: 或者 archivedDataWithRootObject: 来归档类。
NSKeyedUnarchiver 中使用narchiveObjectWithFile: 或者 unarchiveObjectWithData: 来反归档类。
归档系统自带的类
因NSString、NSArray、NSData、NSDictionary 都实现了NSCoding协议,可直接通过调用writeToFile归档。
NSString *str = @"hello";
[str writeToFile:@"/Users/sdh/Desktop/str.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSArray *arr = [[NSArray alloc]initWithObjects:@"lili",@"tata", nil];
NSURL *localUrl = [NSURL fileURLWithPath:@"/Users/sdh/Desktop/arr.txt"];//本地路径
[arr writeToURL:localUrl atomically:YES];//writeToURL相对writeToFile优势在于前者可以远程或本地,而后者只能本地
NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[@"lili",@"男"] forKeys:@[@"name",@"sex"]];
[dict writeToFile:@"/Users/sdh/Desktop/dict.txt" atomically:YES];
归档自定义的类
首先实现NSCoding协议,重写encodeWithCode方法和initWithCode方法,然后通过NSKeyedArchiver转换为NSData,再通过NSData的writeToFile方法写入到文件,
或者将转换后的NSData放入到NSArray或NSDictionary中调用writeToFile写入到文件便可实现包装了自定义类型的数据和字典的归档。
Person类定义
@interface Person : NSObject<NSCoding>//实现NSCoding协议
@property(assign,nonatomic)int age;
@property(copy,nonatomic)NSString *name;
@end
@implementation Person
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeInt:self.age forKey:@"age"];
[aCoder encodeObject:self.name forKey:@"name"];
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
if(self = [super init]) {
self.age = [aDecoder decodeIntForKey:@"age"];
self.name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
@end
Person *aPerson = [[Person alloc]init];
aPerson.age = 20;
aPerson.name = @"sdh";
//归档
NSData *aData = [NSKeyedArchiver archivedDataWithRootObject:aPerson];
NSUserDefaults *uDefaults = [NSUserDefaults standardUserDefaults];//也可以将归档后的数据存储到NSUserDefaults数据库中
[uDefaults setObject:aData forKey:@"archive"];
[uDefaults synchronize];
//反归档
NSData *personData = [uDefaults objectForKey:@"archive"];
Person *uPerson = [NSKeyedUnarchiver unarchiveObjectWithData:personData];
//自定义类与系统类组合一起
NSDictionary *dictPerson = [NSDictionary dictionaryWithObjects:@[[NSKeyedArchiver archivedDataWithRootObject:parent],[NSKeyedArchiver archivedDataWithRootObject:child]] forKeys:@[@"parent",@"child"]];
[dictPerson writeToFile:@"/Users/lili/Desktop/dictPerson.txt" atomically:YES];
NSDictionary *pdict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/lili/Desktop/dictPerson.txt"];//dictionaryWithContentsOfFile
Person *tPerson = [NSKeyedUnarchiver unarchiveObjectWithData:[pdict objectForKey:@"parent"]];
NSArray *arrPerson = [[NSArray alloc]initWithObjects:[NSKeyedArchiver archivedDataWithRootObject:parent],[NSKeyedArchiver archivedDataWithRootObject:parent], nil];
[arrPerson writeToFile:@"/Users/lili/Desktop/arrPerson.txt" atomically:YES];
NSArray *pArr = [NSArray arrayWithContentsOfFile:@"/Users/lili/Desktop/arrPerson.txt"];//arrayWithContentsOfFile
Person *aPerson = [NSKeyedUnarchiver unarchiveObjectWithData:[pArr objectAtIndex:0]];
采用encodeObject方式归档
Person *aPerson = <#Get a Person#>;
NSString *archivePath = <Path for the archive#>;
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:aPerson forKey:ASCPersonKey];
[archiver encodeInt:100 forKey:ASCNumKey];
[archiver finishEncoding];
NSURL *archiveURL = <URL for the archive#>;
BOOL result = [data writeToURL:archiveURL atomically:YES];
采用decodeObjectForKey方式反归档
NSURL *archiveURL = <URL for the archive#>;
NSData *data = [NSData dataWithContentsOfURL:archiveURL];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
// Customize the unarchiver.
Person *aPerson = [unarchiver decodeObjectForKey:ASCPersonKey];
int num = [unarchiver decodeIntForKey:ASCNumKey];
[unarchiver finishDecoding];
文件的创建
//设定文本框存储文件的位置
NSString *strFilePath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
//指定存储文件的文件名
NSString *fileName=[strFilePath stringByAppendingPathComponent:@"test.txt"];
//文件管理器
NSFileManager *fmaneger=[NSFileManager defaultManager];
if ([fmaneger fileExistsAtPath:[self getFilePath]])
{
self.txtField.text=[NSString stringWithContentsOfFile:[self getFilePath] encoding:NSUTF8StringEncoding error:nil];
}
文件的写入
[self.txtField.text writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:nil];
文件的读取
NSFileManager *fmanager=[NSFileManager defaultManager];
if ([fmanager fileExistsAtPath:fileName]) {
[fmanager createFileAtPath:fileName contents:nil attributes:nil];
}
文件的移动
//目标文件夹
NSString *destPath=NSTemporaryDirectory();
//目标文件路径
NSString * destFilePath=[destPath stringByAppendingPathComponent:@"test.txt"];
BOOL result=[fmanager moveItemAtPath:filePath toPath:destFilePath error:nil];
if (result) {
NSLog(@"移动成功");
}
else
{
NSLog(@"移动失败!");
}
文件的删除
NSFileManager *fmanager=[NSFileManager defaultManager];
[fmanager removeItemAtPath:filePath error:nil];