归档就是将我们所使用的变量或者对象以一定的格式写入文件进行存储,等到需要的时候读出来进行还原。
代码展示:
#define PATH @"/Users/md101/Desktop"
#define ERROR(A) if(A){NSLog(@"%@",A);}
int main ()
{
@autoreleasepool {
//将字典中的内容写入文件
/*NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3", nil];
[dict writeToFile:[NSString stringWithFormat:@"%@/testfile/temp.m",PATH] atomically:YES];
//将文件中的内容读入字典
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/testfile/temp.m",PATH]];
NSLog(@"%@",dict);*/
//当有大量的对象或数组等需要进行归档时需要使用辅助的NSKeyedArchieve
//将数组与字典归档到同一个文件中
NSArray *array = [[NSArray alloc] initWithObjects :@"one",@"two",@"three",nil];
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3", nil];
NSMutableData *date = [[NSMutableData alloc] init];
//archiver相当于一个管理员将多个对象或数组等连在一起,放到date库中
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:date];
[archiver encodeObject:array forKey:@"array"];
[archiver encodeObject:dict forKey:@"dict"];
[archiver finishEncoding];
[date writeToFile:[NSString stringWithFormat:@"%@/testfile/temp1.m",PATH] atomically:YES];
//从文件中读取多个数组或者对象
date = [[NSMutableData alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/testfile/temp1.m",PATH]];
NSKeyedUnarchiver *unarhiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:date];
NSArray *array1 = [unarhiver decodeObjectForKey: @"array"];
NSLog(@"%@",array1);
}
return 0;
}