一、Mac OS X从版本10.2开始支持带键的档案。在此之前,要使用NSKeyedArchiver类创建连续的归档。连续的归档需要完全按照写入时的顺序读取归档中的数据。在带键归档中,每个归档字段都有一个名称。归档某个对象时,会为它提供一个名称,即键。从归档中检索该对象时,是根据这个键来检索的。这样可以按照任意的顺序将对象写入归档并进行检索。。
//准备数据,进行归档
NSArray *array = @[@"123",@"abc",@"ABC"];
NSString *string = @"i am a string";
//创建文件保存路径
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *multiPath = [cachePath stringByAppendingPathComponent:@"multi.archiver"];
//初始化一个归档对象和一个NSMutableData联系起来(可归档多个对象)
NSMutableData *writeData = [NSMutableData data];
NSKeyedArchiver *keyedArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:writeData];
//对多个对象进行归档
[keyedArchiver encodeObject:array forKey:@"array"];
[keyedArchiver encodeObject:string forKey:@"string"];
//归档对象完成所有归档后调用*****
[keyedArchiver finishEncoding];
//把归档后的数据写入文件
[writeData writeToFile:multiPath atomically:YES];
//解档多对象数据
//获取文件内容
NSData *writeData2 = [NSData dataWithContentsOfFile:multiPath];
//初始化一个解归档对象,使之和一个NSData联系起来
NSKeyedUnarchiver *keyedUnarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:writeData2];
//解档具体对象
NSString *readstring = [keyedUnarchiver decodeObjectForKey:@"string"];
NSArray *readarray = [keyedUnarchiver decodeObjectForKey:@"array"];
//完成解档
[keyedUnarchiver finishDecoding];
NSLog(@"%@\n\n%@",readarray,readstring);