首页 > 代码库 > 归档与反归档
归档与反归档
NSArray *array =@[@"归档",@"反归档",@"开始”];
//1.创建归档对象
NSMutableData *data = http://www.mamicode.com/[NSMutableDatadata];
NSKeyedArchiver *archiver = [[NSKeyedArchiveralloc] initForWritingWithMutableData:data];
//2.归档
[archiver encodeObject:perforKey:@"array"];
//3.结束归档,当结束归档之后,再归档无效
[archiver finishEncoding];
[array release];
[archiver release];
//4.获取写入文件路径,没有会自动创建一个
NSString *documentPath =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)firstObject];
NSString *newFiel = [documentPathstringByAppendingPathComponent:@"bb.txt"];
//5.data写入文件
BOOL isSucceed = [datawriteToFile:[selfgetFiel]atomically:YES];
//1.根据文件路径初始化NSMutableData
NSMutableData *Data = http://www.mamicode.com/[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.结束反归档
[unarchiver finishDecoding];
[unarchiver release];
三 .注意
1.如果要对一个类的对象实现归档操作,必须让该类实现NSCoding协议
2.当对象为字符串,数组,字典,集合时,属性的语义特性声明为copy.
3.定义完属性的在给实例变量赋值时,要使用setter方法.
如下例@interface Person : NSObject<NSCoding]]>
@property (nonatomic , copy)NSString *name
归档与反归档