写入数据
//1.文件路径
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"info.plist"];
//1. 有个对象
Student *student = [[Student alloc]init];
student.name = @"11";
student.age = 10;
//2.存储 归档
[NSKeyedArchiver archiveRootObject:student toFile:path];
读取数据
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"info.plist"];
//反归档 ,解档
Student *p = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
注意:
如果使用归档
- 该对象必须遵守NSCoding 协议 编码协议
- 实现 encodeWithCoder方法
- 实现:initWIthCoder方法
实现<NSCoding>协议方法
- (void)encodeWithCoder:(NSCoder *)coder{
[coder encodeObject:self.name forKey:@"name"];
[coder encodeInteger:self.age forKey:@"age"];
}
//反归档只是个过程, 告诉系统你读取的时候,想让别人读取哪些属性
- (instancetype)initWithCoder:(NSCoder *)decoder{
if (self = [super init]) {
self.name = [decoder decodeObjectForKey:@"name"];
self.age = [decoder decodeIntegerForKey:@"age"];
}
return self;
}
网友评论