[__SwiftValue encodeWithCoder:]: 无法识别的选择器发送到实例

[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance

我正在尝试使用以下代码存档字典并出现错误。显然我传递的响应字典有问题,但跟踪没有说明任何问题。我如何确定根本原因?

do {
    let data = try NSKeyedArchiver.archivedData(withRootObject: response, requiringSecureCoding: false)
} catch {
    NSLog("Unable to archive  \(error)")
}   

错误:

2019-07-17 19:08:38.978954+0530 MyApp-Swift[372:16845] Unable to archive  Error Domain=NSCocoaErrorDomain Code=4866 "Caught exception during archival: -[__SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x282995e00
    (
    0   CoreFoundation                      0x00000001ca149ebc  + 252
    1   libobjc.A.dylib                     0x00000001c9319a50 objc_exception_throw + 56
    2   CoreFoundation                      0x00000001ca062b14  + 0
    3   CoreFoundation                      0x00000001ca14f7bc  + 1412
    4   CoreFoundation                      0x00000001ca15146c _CF_forwarding_prep_0 + 92
    5   Foundation                          0x00000001cabc4aa8  + 1276
    6   Foundation                          0x00000001caadc3b4  + 444
    7   Foundation                          0x00000001cab08ed8  + 964
    8   Foundation                          0x00000001cabc4aa8  + 1276
    9   Foundation                          0x00000001caadc3b4  + 444
    10  Foundation                          0x0000000

NSKeyedArchiver 仅适用于 Cocoa Objective C 个对象。只有 NSCoding 采用者可以使用 NSKeyedArchiver 存档。您将需要一个仅包含 NSCoding 类型的 NSDictionary。好吧,你没有。

补充马特的回答,完全正确。

在我的例子中,我使用了一个符合 Codable 的结构,为了让它工作,我只是将它编码为一个字典 [String: Any]。

将它应用到您的代码中,它会是这样的:

do {
    let encodedResponse = (try? JSONSerialization.jsonObject(with: JSONEncoder().encode(response))) as? [String: Any] ?? [:]
    let data = try NSKeyedArchiver.archivedData(withRootObject: encodedResponse, requiringSecureCoding: false)
} catch {
    NSLog("Unable to archive  \(error)")
}