**第一种方式:对象单一**
//归档
-(void)NSKeyedArchiver{
NSArray *array = [NSArray arrayWithObjects:@"L",@"J",@"F",nil];
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.LJF"];
NSLog(@"%@", filePath);
BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:filePath];
if(success){
NSLog(@"保存成功");
}
}
//解档
-(void)NSKeyedUnarchiver{
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.LJF"];
id array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@",array);
}
**第二种方式:对象多个**
//归档2
-(void)NSKeyedArchiverTwo{
NSArray *array = [NSArray arrayWithObjects:@"L",@"J",@"F", nil];
NSDictionary *dic = @{@"name":array};
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
//编码
[archiver encodeObject:dic forKey:@"dic"];
[archiver encodeObject:array forKey:@"array"];
[archiver encodeInt:100 forKey:@"num"];
[archiver encodeObject:@"LJF" forKey:@"name"];
//完成编码,将上面的归档数据填充到data中,此时data中已经存储了归档对象的数据
[archiver finishEncoding];
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.LJF"];
BOOL success = [data writeToFile:filePath atomically:YES];
if(success){
NSLog(@"归档成功");
}
}
//解档2
-(void)NSKeyedUnarchiverTwo{
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.LJF"];
//读取归档数据
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
//创建解归档对象,对data中的数据进行解归档
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
//解归档
NSArray *array = [unarchiver decodeObjectForKey:@"array"];
NSLog(@"%@",array);
NSDictionary *dic = [unarchiver decodeObjectForKey:@"dic"];
NSLog(@"%@", dic);
NSString *name = [unarchiver decodeObjectForKey:@"name"];
NSLog(@"%@",name);
int value = [unarchiver decodeIntegerForKey:@"num"];
NSLog(@"%d", value);
}
原文:http://blog.csdn.net/tubiebutu/article/details/45568307