标签:
//简单对象可以通过直接写入文件的方式进行存储,复杂对象我们无法直接写入文件,这个时候需要借助归档和反归档
//归档和反归档并不是数据持久化的方式,而是将复杂对象转化成简单对象的一种方式
Person * per = [Person new];
per.name = @"欧阳冰";
per.gender = @"神秘";
per.hobby = @"美女";
per.age = @"21";
//准备一个路径
NSString * path = NSHomeDirectory();
path = [path stringByAppendingString:@"/曹江涛.avi"];
NSLog(@"%@",path);
//创建数据对象,用来存放person
NSMutableData * data = [NSMutableData data];
//创建归档对象
NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
//归档
[archiver encodeObject:per forKey:@"secret"];
//完成归档
[archiver finishEncoding];
//写入文件(writeToFile)
[data writeToFile:path atomically:YES];
//反归档
NSData * _data = [NSData dataWithContentsOfFile:path];
//创建反归档对象
NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:_data];
//反归档数据
Person * per1 = [unarchiver decodeObjectForKey:@"secret"];
//反归档完成
[unarchiver finishDecoding];
NSLog(@"%@",per1.name);
标签:
原文地址:http://www.cnblogs.com/songtingting/p/4925053.html