1、持久化一个对象(该对象必须实现NSCoding协议)
主要使用 NSData类中 [ NSMutableData* writeToFile:path atomically:YES],关键是怎么位data赋值
一下是完整的代码:
储存:
NSString* p = [self getFilePath]; //构建储存路径
NSLog(@"%@",p);
NSMutableData* data = [[NSMutableData alloc]init]; //构建空数据块(NSMutableData)
NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; //创建打包器(NSKeyedArchiver) 与 空数据块(NSMutableData)关联
YMPerson *person = [[YMPerson alloc] init]; //构建实际的数据
person.name = [_et_name text];
person.age = [_et_age.text intValue];
person.gender = [_et_set text];
[archiver encodeObject:person]; //将数据打包到数据块中
[archiver finishEncoding];
[data writeToFile:p atomically:YES]; //数据块写到磁盘中
读取:
NSMutableData* data = [[NSMutableData alloc] initWithContentsOfFile:[self getFilePath]]; //构建数据储存区块
NSKeyedUnarchiver*unachiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; //构建解包器与数据区块关联
YMPerson *person = [unachiver decodeObject]; //读取对象
_et_set.text =person.gender;
_et_age.text = [NSString stringWithFormat:@"%d",person.age];
_et_name.text=person.name;
NSLog(@"%@",person);
2.持久化多个对象
写入:
NSMutableArray* array =[[NSMutableArray alloc] init]; //构建数据储存容器
YMPerson* person1 = [YMPerson initWithName:@"name1" withAge:20 withGender:@"man"];
YMPerson* person2 = [YMPerson initWithName:@"name2" withAge:22 withGender:@"manman"];
[array addObject:person1];
[array addObject:person2]; //添加实际储存的数据
[NSKeyedArchiver archiveRootObject:array toFile:[self getFilePath] ]; //写入磁盘
读取:
NSArray* persons = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getFilePath]];
for (YMPerson *p in persons) {
NSLog(@"%@,%d,%@",p.name,p.age,p.gender);
}