ios 开发收藏

NSKeyedArchiver

2016-08-11  本文已影响1053人  CoderRH

归档Foundation框架的对象

NSArray *arr = [NSArray arrayWithObjects:@”a”,@”b”,nil];
[NSKeyedArchiver archiveRootObject:arr toFile:path];
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];

归档与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];
上一篇 下一篇

猜你喜欢

热点阅读