1.介紹
一種可以把任意對象直接保存到文件的方式琅坡。
歸檔:把對象保存到文件中雄坪。
解檔:從文件中讀取對象孵户。
2.注意:
歸檔會先清空文件嘁圈,然后重新寫入逗扒。
3.歸檔對象的寫法
1.對象要實現 NSCoding 協議
@interface Student : NSObject<NSCoding>
@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign) CGFloat score;
@property(nonatomic,assign) BOOL sex;
@end
//1.基類寫法
/**
* 告訴系統需要歸檔的屬性
*
* @param aCoder 解析器
*/
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeFloat:self.score forKey:@"score"];
[aCoder encodeBool:self.sex forKey:@"sex"];
}
/**
* 告訴系統解檔出來的數據都需要怎么賦值
*
* @param aDecoder 解析器
*
* @return 對象
*/
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.score = [aDecoder decodeFloatForKey:@"score"];
self.sex = [aDecoder decodeBoolForKey:@"sex"];
}
return self;
}
//1.子類寫法
- (void)encodeWithCoder:(NSCoder *)aCoder{
//一定要調用一下父類的方法
[super encodeWithCoder: aCoder];
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeFloat:self.score forKey:@"score"];
[aCoder encodeBool:self.sex forKey:@"sex"];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
//一定要調用一下父類的方法
if (self = [super initWithCoder: aDecoder]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.score = [aDecoder decodeFloatForKey:@"score"];
self.sex = [aDecoder decodeBoolForKey:@"sex"];
}
return self;
}
4.歸檔 -- NSKeyedArchiver
//歸檔一個對象
- (void)save{
//1.準備對象
Student *stu = [[Student alloc] init];
stu.name = @"zhangsan";
stu.score = 90;
stu.sex = YES;
//2.要存儲的文件路徑
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
filePath = [filePath stringByAppendingPathComponent:@"student.data"];
//3.歸檔
[NSKeyedArchiver archiveRootObject:stu toFile:filePath];
}
//歸檔一組對象
- (void)save{
//1.準備對象
Student *stu = [[Student alloc] initWithName:@"zhangsan" withScore:90 withSex:YES];
Student *stu1 = [[Student alloc] initWithName:@"lisi" withScore:90 withSex:YES];
NSArray *arr = @[stu,stu1];
//2.要存儲的文件路徑
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
filePath = [filePath stringByAppendingPathComponent:@"student.data"];
//3.歸檔
[NSKeyedArchiver archiveRootObject:arr toFile:filePath];
}
5.解檔 -- NSKeyedUnarchiver
//解析單一對象
- (void)getData{
//1.要存儲的文件路徑
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
filePath = [filePath stringByAppendingPathComponent:@"student.data"];
//2.解檔
Student *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
//解檔一組對象
- (void)getData{
//2.要存儲的文件路徑
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
filePath = [filePath stringByAppendingPathComponent:@"student.data"];
//3.解檔
NSArray *stus = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@",stus);
}