一.归档操作
NSArray *array =
@[@"归档",@"反归档",@"开始”];
//1.创建归档对象
NSMutableData *data = [NSMutableData
data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver
alloc] initForWritingWithMutableData:data];
//2.归档
[archiver encodeObject:per
forKey:@"array"];
//3.结束归档,当结束归档之后,再归档无效
[archiver finishEncoding];
[array release];
[archiver release];
//4.获取写入文件路径,没有会自动创建一个
NSString *documentPath =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES)firstObject];
NSString *newFiel = [documentPath
stringByAppendingPathComponent:@"bb.txt"];
//5.data写入文件
BOOL isSucceed = [data
writeToFile:[self
getFiel]
atomically:YES];
二.反归档操作
//1.根据文件路径初始化NSMutableData
NSMutableData *Data = [NSMutableData
dataWithContentsOfFile:/Users/lanouhn/Library/Application Support/iPhone Simulator/7.1/Applications/300BEFD5-1F93-47A3-A1B3-936195FAA53F];
//2.创建一个反归档类
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver
alloc]
initForReadingWithData:Data];
//3.反归档
NSArray *array = [unarchiver
decodeObjectForKey:@"array"];
//4.结束反归档
[unarchiver finishDecoding];
[unarchiver release];
三 .注意
1.如果要对一个类的对象实现归档操作,必须让该类实现NSCoding协议
2.当对象为字符串,数组,字典,集合时,属性的语义特性声明为copy.
3.定义完属性的在给实例变量赋值时,要使用setter方法.
如下例
@interface Person : NSObject<NSCoding]]>
@property (nonatomic , copy)NSString *name