数据存储,model 对象归档本地化
-
(IBAction)saveBtnOnclick:(UIButton *)sender {
Student *student=[[Student alloc]init];
student.name=@"bp";
student.age=25;
student.height=1.9;
student.weight=62;//获取文件路径
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path=[docPath stringByAppendingPathComponent:@"student.bp"];//将自定义的对象保存到文件
[NSKeyedArchiver archiveRootObject:student toFile:path];
} -
(IBAction)readBtnOnclick:(UIButton *)sender {
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path=[docPath stringByAppendingPathComponent:@"student.bp"];//从文件中读取对象
Student *student=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@ %D %.1f %f",student.name,student.age,student.height,student.weight);
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeDouble:self.height forKey:@"height"];
[aCoder encodeFloat:self.weight forKey:@"weight"];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
if (self=[super init]) {
self.name=[aDecoder decodeObjectForKey:@"name"];
self.age=[aDecoder decodeIntegerForKey:@"age"];
self.height=[aDecoder decodeDoubleForKey:@"height"];
self.weight=[aDecoder decodeFloatForKey:@"weight"];
}
return self;
}