NSCoding
NSCoding是把数据存储在iOS和Mac OS上的一种极其简单和方便的方式,它把模型对象直接转变成一个文件,然后再把这个文件重新加载到内存里
/存到本地
Model *model = [[Model alloc] init];
[NSKeyedArchiver archiveRootObject:model toFile:filePath];
//从本地取出
Model *model = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
内部实现
- (void)encodeWithCoder:(NSCoder*)aCoder{
[aCoder encodeObject:self.title forKey:@"title"];
[aCoder encodeObject:self.author forKey:@"another"];
}
- (nullableinstancetype)initWithCoder:(NSCoder*)aDecoder{
self= [super init];
if(self) {
self.title = [aDecoder decodeObjectForKey:@"title"];
self.author = [aDecoder decodeObjectForKey:@"another"];
self.isPublished = [aDecoder decodeBoolForKey:@"isPublished"]; }
return self;
}
NSSecureCoding
NSSecureCoding是NSCoding的进阶,NSCoding毕竟不太安全,大部分支持NSCoding的系统对象都已经升级到支持NSSecureCoding了,如AFNetworking的AFURLSessionManager 例如:
NSData*data = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver*unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
[unarchiver setRequiresSecureCoding:YES];
//解码Model *model = [unarchiver decodeObjectForKey:NSKeyedArchiveRootObjectKey];
内部实现
- (void)encodeWithCoder:(NSCoder*)aCoder{
[aCoder encodeObject:self.title forKey:@"title"];
[aCoder encodeObject:self.author forKey:@"another"];
}
- (nullableinstancetype)initWithCoder:(NSCoder*)aDecoder{
self= [super init];
if(self) {
self.title = [aDecoder decodeObjectForKey:@"title"];
self.author = [aDecoder decodeObjectForKey:@"another"];
}
returnself;
}
+ (BOOL)supportsSecureCoding{
returnYES;
}