ErrorDomain =NSCocoaErrorDomain Code=4864 “value for key ‘XXX’ was of unexpected class ‘XXX ‘. The problem of

The situation is as follows:

Declare a TestModel object that inherits from NSObject and follows the NSSecureCoding protocol

Rewrite the following method to use YYModel implementation

  • - (void)encodeWithCoder:(NSCoder *)coder
  • - (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder
  • + (BOOL)supportsSecureCoding

ViewContrller implements the following methods:

An error is reported when the code is run and the object cannot be retrieved

Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'modelDic' was of unexpected class 'NSDictionary'. Allowed classes are '{( TestModel )}'

Guess what:

  • YYModelObjects are treated as dictionaries when coded
  • YYModelThe dictionary is recognized as the target object when decoding
  • We then need to explicitly specify the type of the member variable.


Solutions are as follows:

Method one: use unarchivedObjectOfClasses: fromData: error: the solution file (recommended)

Method two: Use NSOject as the unfile target type and receive