Foundation--NSKeyedArchiver与NSKeyedUnarchiver

//归档数据,并用二进制写入文件
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *keyedArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[keyedArchiver encodeObject:Users forKey:@"users"];//Users已知的保存用户信息的数组
[keyedArchiver finishEncoding];
[data writeToFile:@"归档数据保存路径" atomically:YES];
//读取上面已经保存好的文件,并反归档后在程序中使用数据
NSData *newData = [NSData dataWithContentsOfFile:@"归档数据保存路径"];
NSKeyedUnarchiver *keyedUnArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:newData];
NSArray *users = [keyedUnArchiver decodeObjectForKey:@"users"];
for (User *user in users) {
	NSLog(@"name = %@  pw = %@",u.name,u.password);
}


注意:需要归档的数据中如果含有自定义的对象,那么该对象需遵守<NSCoding>协议,并重写如下方法:

- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:对象属性 forKey:@"归档的key"];
}
- (id)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        实例变量 = [aDecoder decodeObjectForKey:@"归档的key"];
    }
    return self;
}



你可能感兴趣的:(ios,Foundation)