标签:类型 orm 数据区 nsarray cti ctf cal roo ble
如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,可以直接用NSKeyedArchiver进行归档和恢复
不是所有的对象都可以直接用这种方法进行归档,只有遵守了NSCoding协议的对象才可以
归档一个NSArray对象到Documents/array.archive
NSArray *arr = [NSArray arrayWithObjects:@”a”,@”b”,nil];
[NSKeyedArchiver archiveRootObject:arr toFile:path];
恢复(解码)NSArray对象
NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
//归档的时候调用
- (void)encodeWithCoder:(NSCoder *)encoder {
//先归档父类
[super encodeWithCode:encode];
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeInt:self.age forKey:@"age"];
[encoder encodeFloat:self.height forKey:@"height"];
}
//解归档的时候调用
- (id)initWithCoder:(NSCoder *)decoder {
//先解归档父类
self = [super initWithCoder:decoder];
self.name = [decoder decodeObjectForKey:@"name"];
self.age = [decoder decodeIntForKey:@"age"];
self.height = [decoder decodeFloatForKey:@"height"];
return self;
}
//归档(编码)
Person *person = [[Person alloc] init];
person.name = @"rh";
person.age = 100;
person.height = 1.83f;
[NSKeyedArchiver archiveRootObject:person toFile:path];
//恢复(解码)
Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
使用archiveRootObject:toFile:方法可以将一个对象直接写入到一个文件中,但有时候可能想将多个对象写入到同一个文件中,那么就要使用NSData来进行归档对象
多个对象归档
//归档(编码)
// 新建一块可变数据区
NSMutableData *data = [NSMutableData data];
// 将数据区连接到一个NSKeyedArchiver对象
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// 开始存档对象,存档的数据都会存储到NSMutableData中
[archiver encodeObject:person1 forKey:@"person1"];
[archiver encodeObject:person2 forKey:@"person2"];
// 存档完毕(一定要调用这个方法)
[archiver finishEncoding];
// 将存档的数据写入文件
[data writeToFile:path atomically:YES];
//恢复(解码)
// 从文件中读取数据
NSData *data = [NSData dataWithContentsOfFile:path];
// 根据数据,解析成一个NSKeyedUnarchiver对象
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
Person *person1 = [unarchiver decodeObjectForKey:@"person1"];
Person *person2 = [unarchiver decodeObjectForKey:@"person2"];
// 恢复完毕
[unarchiver finishDecoding];
标签:类型 orm 数据区 nsarray cti ctf cal roo ble
原文地址:http://www.cnblogs.com/Free-Thinker/p/7126297.html