创建一个工程,使用两种方式来进行数据归档。
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = NSHomeDirectory();
NSLog(@"Path is : %@", path);
NSString *filepath = [path stringByAppendingPathComponent:@"testing.archiver"];
NSLog(@"File path is : %@", filepath);
//1 arachive use NSData
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:@"123test"];
[data writeToFile:filepath atomically:YES];
NSLog(@"The first way is done");
//2 to write the data into archived file directly
[NSKeyedArchiver archiveRootObject:@"test123" toFile:filepath];
NSLog(@"The second way is done");
//unarchive the file
//way one
NSLog(@"The first way is : %@", [NSKeyedUnarchiver unarchiveObjectWithData:data]);
//way two
NSLog(@"The second way is :%@",[NSKeyedUnarchiver unarchiveObjectWithFile:filepath]);
// Do any additional setup after loading the view, typically from a nib.
}
Log文件:
2018-03-22 10:11:25.766242+0800 TOCArchiveda[14452:774363] Path is : /Users/xxx/Library/Developer/CoreSimulator/Devices/39B6xxxx-xxxx-xxxx-xxxx-xxxx5D1FE8D5E/data/Containers/Data/Application/2EA9A4E4-F1B9-4BFC-9399-8D57E941C798
2018-03-22 10:11:25.766435+0800 TOCArchiveda[14452:774363] File path is : /Users/xxxx/Library/Developer/CoreSimulator/Devices/39B6xxxx-xxxx-xxxx-xxxx-xxxx5D1FE8D5E/data/Containers/Data/Application/2EA9xxxx-xxxx-xxxx-xxxx-xxxxE941C798/testing.archiver
2018-03-22 10:11:25.767682+0800 TOCArchiveda[14452:774363] The first way is done
2018-03-22 10:11:25.768667+0800 TOCArchiveda[14452:774363] The second way is done
2018-03-22 10:11:25.769092+0800 TOCArchiveda[14452:774363] The first way is : 123test
2018-03-22 10:11:25.769428+0800 TOCArchiveda[14452:774363] The second way is :test123