所谓归档,就是把我们平时使用的变量或者对象以一定的格式写入文件中进行存储,等到需要时直接读出来就能还原成原对象的格式。说得通俗点就是比如说一个字典以一个键值对的形式存储的我们把它以一定格式写到文件里键有键的位置,值放到值的位置等我们把它读出来的时候又能恢复能一个字典不需要转换,这种形为就是归档。
#define PATH @"/Users/lijun/Desktop/dir/file.plist"
//我们把一个字典写到plist文件里
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"One",@"1",@"Two",@"2",@"Three",@"3", nil];
[dict writeToFile:PATH atomically:YES];
[dict release];
NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:PATH];//根据plist文件里的内容创建一个字典
//如果处理一些比较复杂的数据就需要用NSKeyedArchiver了
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"One",@"1",@"Two",@"2",@"Three",@"3", nil];
NSArray *array = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",nil];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:dict forKey:@"dict"];
[archiver encodeObject:array forKey:@"array"];
[archiver finishEncoding];
[data writeToFile:PATH atomically:YES];
//解档
NSData *data = [[NSData alloc] initWithContentsOfFile:PATH];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSArray *array = [unarchiver decodeObjectForKey:@"array"];
NSDictionary *dict = [unarchiver decodeObjectForKey:@"dict"];
我们就完成一个归档解档的过程
如果是一个普通的类的对象不再是数组或字典我们如何归档要想一个类的对象能够被归档,这个类必须遵从NSCoding协议并且实现协议的两个方法
@interface Human : NSObject<NSCoding>
{
}
@property int age;
@property (copy) NSString *name;
@property (retain) Human *child;
@end
#import "Human.h"
@implementation Human
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeInt:_age forKey:@"age"];
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeObject:_child forKey:@"child"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init])
{
self.age = [aDecoder decodeIntForKey:@"age"];
self.name = [aDecoder decodeObjectForKey:@"name"];
self.child = [aDecoder decodeObjectForKey:@"child"];
}
return self;
}
@end
重写这两个方法后就能对human这个类归档操作了Human *human1 = [[Human alloc] init];
Human *human2 = [[Human alloc] init];
human1.age = 20;
human1.name = @"li jun";
human1.child = human2;
NSData *data1 = [NSKeyedArchiver archivedDataWithRootObject:human1];
[data1 writeToFile:@"/Users/lijun/Desktop/dir/file.txt" atomically:YES];
NSData *data2 = [NSData dataWithContentsOfFile:@"/Users/lijun/Desktop/dir/file.txt"];
Human *human3 = [NSKeyedUnarchiver unarchiveObjectWithData:data2];
NSLog(@"%@ %d",human3.name,human3.age);
这样我们就完成了一个普通类对象的归档和解档。