您的位置:首页 > 其它

归档 & 反归档

2015-08-25 18:15 288 查看
如果想要实现归档和反归档的操作需要签订一个协议 NSCoding

[NSKeyedArchiver archiveRootObject:stuArr toFile:documentPath]; // 归档(写入)

- (void)encodeWithCoder:(NSCoder
*)aCoder { // 归档

[aCoder encodeObject:self.name forKey:@"姓名"];
[aCoder encodeObject:self.sex forKey:@"性别"];
[aCoder encodeObject:self.hobby forKey:@"爱好"];
[aCoder encodeInteger:self.age forKey:@"年龄"];
}

NSArray *studentArray = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];
// 反归档(读取)
- (id)initWithCoder:(NSCoder *)aDecoder { // 反归档
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"姓名"];
self.age = [aDecoder decodeIntegerForKey:@"年龄"];
self.hobby = [aDecoder decodeObjectForKey:@"爱好"];
self.sex = [aDecoder decodeObjectForKey:@"性别"];
}
return self;
}

存储与读取的两个button 的绑定方法

- (IBAction)save:(UIButton *)button {

MSPersonModel *person = [MSPersonModel personWithName:@"唐启哲" age:19];

NSString *rootPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];

NSString *allPath = [rootPath stringByAppendingPathComponent:@"person.data"];

[NSKeyedArchiver archiveRootObject:person toFile:allPath];

}

- (IBAction)read:(UIButton *)button {

NSString *rootPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)[0];

NSString *allPath = [rootPath stringByAppendingPathComponent:@"person.data"];(若是person.plist文件 可加载一个数组)

MSPersonModel *person = [NSKeyedUnarchiver unarchiveObjectWithFile:allPath];

NSLog(@"%@ ---- %li", person.name, person.age);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: