归档
归档
基本概念
- 对象归档是指将对象写入文件保存在硬盘上,当再次重新打开程序时,可以还原这些对象。你也可以称他为对象序列化,对象持久化。
- 数据持久性的方式
- NSKeyedArchiver --- 对象归档
- NSUserDefaults
- 属性列表化(NSArray、NSDictionary保存文件)
- SQlite数据库、Core Data数据库
- 归档的形式
- 对Foundation库中对象进行归档
- 自定义对象进行归档(需要实现归档协议,NSCoding)
- 归档后的文件是加密的,属性列表是明文的。属性列表也不能对自定义对象进行保存。
示例
- 归档(序列化)
//对数组进行归档,归档文件名为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);
自定义内容归档示例
- 归档
- 使用 NSData 实例作为归档的存储数据
- 添加归档的内容(设置key与value)
- 完成归档
- 将归档数据存入磁盘中
- 解归档
- 从磁盘读取文件,生成 NSData 实例
- 根据 Data 实例创建和初始化解归档实例
- 解归档,根据key 访问 value 的值
- 代码实例
- 归档
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);