数据存储之归档
2017-06-09 本文已影响0人
贼海鸥
归档有两种方法:
第一种:一个对象创建一个归档文件,缺点:太麻烦
比如,归档一个数组
NSArray *array = @[@"123" , @"abc" , @"132"];
// 拿到创建用户的根路径
NSString *homePath = NSHomeDirectory();
NSLog(@"%@" , homePath);
NSString *path = [homePath stringByAppendingPathComponent:@"text.yaalv"];
BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:path];
if (success) {
NSLog(@"归档成功");
}
解归档的方法
NSString *homePath = NSHomeDirectory();
NSLog(@"%@" , homePath);
NSString *path = [homePath stringByAppendingPathComponent:@"text.yaalv"];
NSArray *data = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@" , data[0]);
第二种就是建一个归档文件,将要保存的内容归档
NSString *homePath = NSHomeDirectory();
NSLog(@"%@" , homePath);
NSString *filePath = [homePath stringByAppendingPathComponent:@"custom.text"];
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeFloat:50.0 forKey:@"weight"];
// @"李四"这里可以填任很多的数据的数据类型,比如数组什么的
[archiver encodeObject:@"李四" forKey:@"name"];
[archiver encodeInt:12 forKey:@"age"];
[archiver finishEncoding];
BOOL success = [data writeToFile:filePath atomically:YES];
if (success) {
NSLog(@"------归档成功");
}
解归档的方法
NSString *homePath = NSHomeDirectory();
NSLog(@"%@" , homePath);
NSString *filePath = [homePath stringByAppendingPathComponent:@"custom.text"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSString *name = [unarchiver decodeObjectForKey:@"name"];
NSLog(@"name:%@" , name);
本文demo下载:
https://github.com/TheifSeaMew/-.git