iOS开发中常用的数据持久化方案有
- NSUserDefault
- CoreData
- sqlite
- NSFileManager
- NSCoding 归档
本次先探索NSCoding的使用和原理
对象想要成功归档,需要遵循< NSSecureCoding >协议,实现以下方法
- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
// object 可以为nil
[aCoder encodeObject:_array forKey:@"array"];
[aCoder encodeObject:_dict forKey:@"dict"];
[aCoder encodeObject:_str forKey:@"str"];
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder {
self = [super init];
if (self) {
// nil可以被解档
_array = [aDecoder decodeObjectOfClass:[NSArray class] forKey:@"array"];
_dict = [aDecoder decodeObjectOfClass:[NSDictionary class] forKey:@"dict"];
_str = [aDecoder decodeObjectOfClass:[NSString class] forKey:@"str"];
}
return self;
}
// 安全归档必须重写此类方法。
+ (BOOL)supportsSecureCoding
{
return YES;
}
iOS6以后请使用NSSecureCoding,因为NSCoding可能会受到文件替换攻击,安全性不可靠。
A protocol that enables encoding and decoding in a manner that is robust against object substitution attacks.
NSCoder 又是个什么东西呢?
是官方提供的归解档工具NSKeyedArchiver、NSKeyedUnarchiver的父类。
iOS11以后推荐使用以下API,归档使用安全归档,解档提供了类的检查,是更安全的解档方法。
#NSKeyedArchiver
+ (nullable NSData *)archivedDataWithRootObject:(id)object requiringSecureCoding:(BOOL)requiresSecureCoding error:(NSError **)error API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0));
#NSKeyedUnarchiver
+ (nullable id)unarchivedObjectOfClass:(Class)cls fromData:(NSData *)data error:(NSError **)error API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)) NS_REFINED_FOR_SWIFT;
+ (nullable id)unarchivedObjectOfClasses:(NSSet<Class> *)classes fromData:(NSData *)data error:(NSError **)error API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)) NS_REFINED_FOR_SWIFT;
网友评论