iOS項目拆分:數(shù)據(jù)本地持久化(3)

歸檔是將對象轉(zhuǎn)化為數(shù)據(jù)字節(jié), 以文件的形式存儲在磁盤上,是數(shù)據(jù)本地持久化方式中的一種。歸檔數(shù)據(jù)需要用到Model的時候,創(chuàng)建一個繼承與NSObject的類遵循NSCoding協(xié)議。

#pragma mark - 單個對象存儲
NSArray *array = [NSArray arrayWithObjects:@"X教授",@"金剛狼",@"暴風女", nil]; 
NSString *documentPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString * filePath = [documentPath stringByAppendingPathComponent:@"saved"];
// 歸檔 
BOOL result = [NSKeyedArchiver archiveRootObject:array toFile:filePath]; NSLog(@"%d",result); 
// 反歸檔
NSArray *array1 = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; NSLog(@"%@",[array1 objectAtIndex:1]);
#pragma mark - 多個對象存儲成一個文檔
#pragma mark 第一步:將數(shù)據(jù)存到data里面
NSMutableData *data = [NSMutableData new];
 // 創(chuàng)建一個工具對象 
NSKeyedArchiver *archivers = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; 
[archivers encodeObject:@"X戰(zhàn)警" forKey:@"name"]; [archivers encodeObject:@"Movie" forKey:@"type"];
 //標識結(jié)束添加
 [archivers finishEncoding];
#pragma mark 將Data存到文件中 
NSString *dataPath = [self documentFilePathWithInfo];
 [data writeToFile:dataPath atomically:YES];
#pragma mark 還是需要借助工具 
//在工具初始化的時候可以綁定一個數(shù)據(jù)源 
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data]; 
NSString * name = [unarchiver decodeObjectForKey:@"name"];
 NSString * type = [unarchiver decodeObjectForKey:@"type"];
 //標識結(jié)束操作
 [unarchiver finishDecoding];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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