iOS_NSCoding与NSSecureCoding

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;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容