iOS_NSCoding與NSSecureCoding

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;

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容