1、归档
1> 给一个对象归档时,和它有关的对象也需要归档。
2> 可以将多个对象放在一个数组里,然后归档数组。
3> 也可以用NSMutableData方法归档。
多对象归档:
NSMutableData * data = [NSMutableData data];
//根据二进制流创建NSKeyedArchiver对象。
NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
//对对象进行归档操作
[archiver encodeObject:p forKey:@"person1"];
[archiver encodeObject:p2 forKey:@"person2"];
//结束归档
[archiver finishEncoding];
//将二进制流写入文件
[data writeToFile:@"/Users/dahuan/Desktop/test.txt" atomically:YES];
多对象解档:
NSData * data = [NSData dataWithContentsOfFile:@"/Users/dahuan/Desktop/test.txt"];
NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
Person * p = [unarchiver decodeObjectForKey:@"person1"];
Person * p2 = [unarchiver decodeObjectForKey:@"person2"];
[unarchiver finishDecoding];
举例:(person文件看上文)
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"%@",NSTemporaryDirectory());
NSLog(@"%@",NSUserName());
NSLog(@"%@",NSHomeDirectory());
NSLog(@"%@",NSHomeDirectoryForUser(@"dahuan"));
// Person * p = [[Person alloc] init];
// p.name = @"dahuan";
// p.age = 12;
// p.weight = 110.0;
//
// Person * p2 = [[Person alloc] init];
// p2.name = @"dashu";
// p2.age = 18;
// p2.weight = 100.0;
//
// NSMutableData * data = [NSMutableData data];
//
// //根据二进制流创建NSKeyedArchiver对象。
// NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// //对对象进行归档操作
// [archiver encodeObject:p forKey:@"person1"];
// [archiver encodeObject:p2 forKey:@"person2"];
// //结束归档
// [archiver finishEncoding];
// //将二进制流写入文件
// BOOL isSuccess = [data writeToFile:@"/Users/dahuan/Desktop/test.txt" atomically:YES];
//
// if (isSuccess) {
// NSLog(@"归档成功");
// } else {
// NSLog(@"归档失败");
// }
// NSData * data = [NSData dataWithContentsOfFile:@"/Users/dahuan/Desktop/test.txt"];
// NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//
// Person * p = [unarchiver decodeObjectForKey:@"person1"];
// Person * p2 = [unarchiver decodeObjectForKey:@"person2"];
//
// [unarchiver finishDecoding];
//
// NSLog(@"%@",p.name);
// NSLog(@"%d",p.age);
// NSLog(@"%f",p.weight);
//
// NSLog(@"%@",p2.name);
// NSLog(@"%d",p2.age);
// NSLog(@"%f",p2.weight);
// Person * p3 = [[Person alloc] init];
// p3.name = @"dami";
// p3.age = 20;
// p3.weight = 140.0;
//
// NSArray * array = @[p,p2,p3];
//
// BOOL isSuccess = [NSKeyedArchiver archiveRootObject:array toFile:@"/Users/dahuan/Desktop/test.txt"];
// if (isSuccess) {
// NSLog(@"归档成功");
// } else {
// NSLog(@"归档失败");
// }
//解档
// NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/dahuan/Desktop/test.txt"];
//
// for (Person * p in array) {
// NSLog(@"%@",p.name);
// NSLog(@"%d",p.age);
// NSLog(@"%f",p.weight);
// }
}
return 0;
}