NSCoding
NSCoding是把數(shù)據(jù)存儲(chǔ)在iOS和Mac OS上的一種極其簡(jiǎn)單和方便的方式,它把模型對(duì)象直接轉(zhuǎn)變成一個(gè)文件,然后再把這個(gè)文件重新加載到內(nèi)存里
/存到本地
Model *model = [[Model alloc] init];
[NSKeyedArchiver archiveRootObject:model?toFile:filePath];
//從本地取出
Model *model?= [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
內(nèi)部實(shí)現(xiàn)
- (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的進(jìn)階,NSCoding畢竟不太安全,大部分支持NSCoding的系統(tǒng)對(duì)象都已經(jīng)升級(jí)到支持NSSecureCoding了,如AFNetworking的AFURLSessionManager? 例如:
NSData*data = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver*unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
[unarchiver setRequiresSecureCoding:YES];
//解碼Model *model = [unarchiver decodeObjectForKey:NSKeyedArchiveRootObjectKey];
內(nèi)部實(shí)現(xiàn)
- (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;
}