解决 Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'xxx' was of unexpected class 'xxx'.
的问题
情况如下:
声明一个继承于NSObject
的 TestModel
对象,并遵循 NSSecureCoding
协议
重写以下方法,使用YYModel实现
- (void)encodeWithCoder:(NSCoder *)coder
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder
+ (BOOL)supportsSecureCoding
ViewContrller
实现以下方法:
运行代码就会报错,且无法获取到对象
Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'modelDic' was of unexpected class 'NSDictionary'. Allowed classes are '{( TestModel )}'
猜测如下:
YYModel
编码时会把对象作为字典处理YYModel
解码时识别到字典就把它当成目标对象- 那么就需要我们显式指定该成员变量的类型。
解决方法如下:
方法一:使用 unarchivedObjectOfClasses: fromData: error:
解档 (推荐)
方法二:使用NSOject
作为解档目标类型并接收