iOS11以上系统归档存储数据
2019-07-18 本文已影响0人
加盐白咖啡
iOS11以上归档api废弃了老方法,archiveRootObject:toFile: 但是到iOS12还可以用,所以可以用下面新方法代替
- 存储字符串类型
NSError *error = nil;
NSString *docsDir;
NSArray *dirPaths;
// 获取存储路径
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths firstObject];
NSString *databasePath = [docsDir stringByAppendingPathComponent:@"appData.data"];
// iOS12 归档实现代码
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:@"iOS" requiringSecureCoding:NO error:&error];
[data writeToFile:databasePath options:NSDataWritingAtomic error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);
// iOS12 解档实现代码
NSData *newData = [NSData dataWithContentsOfFile:databasePath];
NSString *fooString = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSString class] fromData:newData error:&error];
NSLog(@"%@",fooString);
- 存储自定义对象归档解档
创建Person类继承自NSObject ,遵守NSCoding或者NSSecureCoding协议,重写两个方法。"supportsSecureCoding"是NSSecureCoding协议下的重要属性,如果采用NSSecureCoding协议,必须重写supportsSecureCoding 方法并返回YES
#import "Person.h"
#pragma mark - 实现NSSecureCoding协议
@interface Person () <NSSecureCoding>
@end
@implementation Person
#pragma mark - 归档实现
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:self.name forKey:@"name"];
[coder encodeInt:self.age forKey:@"age"];
}
#pragma mark - 解档实现
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntForKey:@"age"];
}
return self;
}
#pragma mark - 这个必须实现 , 否则解档文件的时候会返回null
+ (BOOL)supportsSecureCoding {
return YES;
}
@end
- 归档
NSError *error = nil;
Person *person = [[Person alloc] init];
person.name = @"小明";
person.age = 10;
// 获取存储路径
NSString *dirPaths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *dataPath = [dirPaths stringByAppendingPathComponent:@"appData.data"];
// 归档实现代码
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:person requiringSecureCoding:NO error:&error];
[data writeToFile:dataPath options:NSDataWritingAtomic error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);
- 解档
NSError *error;
NSString *dirPaths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *databasePath = [dirPaths stringByAppendingPathComponent:@"appData.data"];
NSData *newData = [NSData dataWithContentsOfFile:databasePath];
Person *person = [NSKeyedUnarchiver unarchivedObjectOfClass:Person.class fromData:newData error:&error];
NSLog(@"name=%@,age=%d",person.name,person.age);