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