NSKeyedArchiver-对象归档
对象归档是指将对象写入文件保存在硬盘上,再次打开程序可以还原对象。(序列化、持久化)
归档形式
- 对foundation库中的对象进行归档
- 单一对象
- 归档
NSArray * arr = @[@1, @"sda"]; NSString *homePath = NSHomeDirectory(); NSString *path = [homePath stringByAppendingPathComponent:@"test.j"];// admin/目录下 扩展名随便取都行 bool res = [NSKeyedArchiver archiveRootObject:arr toFile:path]; if(res){ NSLog(@"succes"); }
- 解归档
NSString *home = NSHomeDirectory(); NSString *path = [home stringByAppendingPathComponent:@"test.j"]; NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; NSLog(@"%@", array);
- 缺点:一个归档对应一个解归档,类型多之后不好分辨类型
- 多个对象
- 归档
- 使用NSData实例作为归档的数据存储
- 添加归档的内容(key-value)
- 完成归档
- 将归档数据存入磁盘
NSString *home = NSHomeDirectory(); NSString *path = [home stringByAppendingPathComponent:@"test.j"]; NSMutableData *data = [NSMutableData data]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; NSArray *array = @[@123, @"abc"]; [archiver encodeObject:array forKey:@"nsarray"]; [archiver encodeInt:2 forKey:@"count"]; [archiver finishEncoding]; BOOL res = [data writeToFile:path atomically:NO]; if(res){ NSLog(@"succes"); }
- 解归档
- 从磁盘读取文件,生成NSData实例
- 根据Data实例创建和初始化解归档实例
- 解归档,根据key访问value
NSString *home = NSHomeDirectory(); NSString *path = [home stringByAppendingPathComponent:@"test2.j"]; NSData *data = [NSData dataWithContentsOfFile:path]; NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; 这是老的初始化方式,新的要将安全编码设为NO // NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:data error:nil]; // [unarchiver setRequiresSecureCoding:NO]; int count = [unarchiver decodeIntForKey:@"count"]; NSArray *array = [unarchiver decodeObjectForKey:@"nsarray"]; [unarchiver finishDecoding]; NSLog(@"count = %d, array = %@", count, array);
- 自定义对象进行归档(需要实现归档协议,NSCodeing[类似于java中的serilaizable)
- 实例
// 遵守 NSCoding 协议 @interface Dog : NSObject <NSCoding> @property (nonatomic, assign)int age; @property (nonatomic, copy)NSString *name; + (Dog *)dogWithName:(NSString *)name andAge:(int)age; @end
// 实现 NSCoding 协议方法 @implementation Dog // 归档 方法,使用编码器将对象编码成二进制数据流,归档(持久化存储) - (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeInt:self.age forKey:@"age"]; [aCoder encodeObject:self.name forKey:@"name"]; } // 反归档 方法,将保存在磁盘上的二进制数据流,解码成 OC 对象 - (id)initWithCoder:(NSCoder *)aDecoder{ if(self = [super init]){ self.age = [aDecoder decodeIntForKey:@"age"]; self.name = [aDecoder decodeObjectForKey:@"name"]; } return self; } @end
#import "Dog.h" // 文件路径 NSString *achiverPath = [NSHomeDirectory() stringByAppendingString:@"/Desktop/dogAchiverFile"]; Dog *dog = [Dog dogWithName:@"xiao hei" andAge:5]; // 归档 // 归档到文件 BOOL bl = [NSKeyedArchiver archiveRootObject:dog toFile:achiverPath]; // 反归档 // 从文件反归档 Dog *dogFromAchiverFile = [NSKeyedUnarchiver unarchiveObjectWithFile:achiverPath];
归档后的文件是加密的,属性列表是明文(参考OC中常用的类、数据类型、数据结构及结构体)