//文件路徑
-(NSString *)cachesTestPathWithFileName:(NSString *)fileName{
NSString * homePath=NSHomeDirectory();
NSString * libraryPath=[homePath stringByAppendingPathComponent:@"Library"];
NSString * cachesPath=[libraryPath stringByAppendingPathComponent:@"Caches"];
return [cachesPath stringByAppendingPathComponent:fileName];
}
// 1. 單個對象的歸檔解檔
NSArray * arr=@[@"hello"];
//獲取歸檔路徑
NSString * keyPath=[self cachesTestPathWithFileName:@"arr.key"];
//執行歸檔操作
BOOL rel=[NSKeyedArchiver archiveRootObject:arr toFile:keyPath];
if (rel) {
NSLog(@"完成");
}
//執行解檔操作
NSArray * arrOut=[NSKeyedUnarchiver unarchiveObjectWithFile:keyPath];
// 2.多個對象歸檔到一個文件中
//用于存儲歸檔進的對象數據。
NSMutableData * data=[[NSMutableData alloc]init];
//實例化歸檔對象
NSKeyedArchiver * keyedArchiver=[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
//開始歸檔多個對象
[keyedArchiver encodeObject:@{@"a":@"b"} forKey:@"dic"];
[keyedArchiver encodeDouble:1.414 forKey:@"gen2"];
[keyedArchiver encodeBool:YES forKey:@"bool"];
[keyedArchiver finishEncoding];
//把存儲歸檔數據的data保存到本地
NSString * theDataPath=[self cachesTestPathWithFileName:@"save"];
[data writeToFile:theDataPath atomically:NO];
//多對象解檔
NSData * outData=[NSData dataWithContentsOfFile:theDataPath];
//創建解檔對象
NSKeyedUnarchiver * unArchiver=[[NSKeyedUnarchiver alloc]initForReadingWithData:outData];
NSDictionary * outDic=[unArchiver decodeObjectForKey:@"dic"];
NSLog(@"%@",outDic);
NSLog(@"%f",[unArchiver decodeDoubleForKey:@"gen2"]);
在 .h 文件中
//自定義類,想要實現歸檔接檔,要遵守NSCoding協議
@interface Student : NSObject
<NSCoding>
@property (nonatomic,copy) NSString * name;
@property (nonatomic) float score;
@end
在 .m 文件中
//實現歸檔協議方法
-(void)encodeWithCoder:(NSCoder *)aCoder{
//對屬性進行歸檔操作
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeFloat:self.score forKey:@"score"];
}
//實現解檔協議方法
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self=[super init]) {
//把自身屬性重新賦值。
self.name=[aDecoder decodeObjectForKey:@"name"];
self.score=[aDecoder decodeFloatForKey:@"score"];
}
return self;
}
@end
// 3. 實現自定義類的歸檔和解檔
Student * stu=[[Student alloc]init];
stu.name=@"小明";
stu.score=80;
//歸檔
NSString * stuPath=[self cachesTestPathWithFileName:@"stu.key"];
[NSKeyedArchiver archiveRootObject:stu toFile:stuPath];
//解檔
Student * outStu=[NSKeyedUnarchiver unarchiveObjectWithFile:stuPath];
NSLog(@"%@ %f",outStu.name,outStu.score);
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。