//文件路徑
-(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"];
//執(zhí)行歸檔操作
BOOL rel=[NSKeyedArchiver archiveRootObject:arr toFile:keyPath];
if (rel) {
NSLog(@"完成");
}
//執(zhí)行解檔操作
NSArray * arrOut=[NSKeyedUnarchiver unarchiveObjectWithFile:keyPath];
// 2.多個對象歸檔到一個文件中
//用于存儲歸檔進(jìn)的對象數(shù)據(jù)讯榕。
NSMutableData * data=[[NSMutableData alloc]init];
//實(shí)例化歸檔對象
NSKeyedArchiver * keyedArchiver=[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
//開始?xì)w檔多個對象
[keyedArchiver encodeObject:@{@"a":@"b"} forKey:@"dic"];
[keyedArchiver encodeDouble:1.414 forKey:@"gen2"];
[keyedArchiver encodeBool:YES forKey:@"bool"];
[keyedArchiver finishEncoding];
//把存儲歸檔數(shù)據(jù)的data保存到本地
NSString * theDataPath=[self cachesTestPathWithFileName:@"save"];
[data writeToFile:theDataPath atomically:NO];
//多對象解檔
NSData * outData=[NSData dataWithContentsOfFile:theDataPath];
//創(chuàng)建解檔對象
NSKeyedUnarchiver * unArchiver=[[NSKeyedUnarchiver alloc]initForReadingWithData:outData];
NSDictionary * outDic=[unArchiver decodeObjectForKey:@"dic"];
NSLog(@"%@",outDic);
NSLog(@"%f",[unArchiver decodeDoubleForKey:@"gen2"]);
在 .h 文件中
//自定義類徽诲,想要實(shí)現(xiàn)歸檔接檔,要遵守NSCoding協(xié)議
@interface Student : NSObject
<NSCoding>
@property (nonatomic,copy) NSString * name;
@property (nonatomic) float score;
@end
在 .m 文件中
//實(shí)現(xiàn)歸檔協(xié)議方法
-(void)encodeWithCoder:(NSCoder *)aCoder{
//對屬性進(jìn)行歸檔操作
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeFloat:self.score forKey:@"score"];
}
//實(shí)現(xiàn)解檔協(xié)議方法
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self=[super init]) {
//把自身屬性重新賦值闷尿。
self.name=[aDecoder decodeObjectForKey:@"name"];
self.score=[aDecoder decodeFloatForKey:@"score"];
}
return self;
}
@end
// 3. 實(shí)現(xiàn)自定義類的歸檔和解檔
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);
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者