归档
基本概念
- 对象归档是指将对象写入文件保存在硬盘上,当再次重新打开程序时,可以还原这些对象。你也可以称他为对象序列化,对象持久化。
示例
//对数组进行归档,归档文件名为temparray 后缀名可以任意
NSString *homeDirectory = NSHomeDirectory();
NSArray *array = @[@123,@234,@"abc",@"hello"];
NSString *filepath = [homeDirectory stringByAppendingPathComponent:@"temparray.adsf"];
if([NSKeyedArchiver archiveRootObject:array toFile:filepath])
{
NSLog(@"归档成功");
}
//解密刚刚的归档内容
NSString *homeDirectory = NSHomeDirectory();
NSString *filepath = [homeDirectory stringByAppendingPathComponent:@"temparray.adsf"];
NSArray *unArray = [NSKeyedUnarchiver unarchiveObjectWithFile:filepath];
NSLog(@"解归档内容 %@",unArray);自定义内容归档示例
NSString *homeDirectory = NSHomeDirectory();
NSString *directoryA = [homeDirectory stringByAppendingPathComponent:@"data.archive"];
//自定义归档
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeFloat:50 forKey:@"weight"];
[archiver encodeObject:@"jack" forKey:@"name"];
[archiver finishEncoding];
[data writeToFile:directoryA atomically:YES];
NSString *homeDirectory = NSHomeDirectory();
NSString *directoryA = [homeDirectory stringByAppendingPathComponent:@"data.archive"];//解归档
NSData *data = [NSData dataWithContentsOfFile:directoryA];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
float weight = [unarchiver decodeFloatForKey:@"weight"];
NSString *name = [unarchiver decodeObjectForKey:@"name"];
NSLog(@"weight is %f",weight);
NSLog(@"name is %@", name);