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

时间:2019-07-17 14:15:41

标签: ios swift nsdata nskeyedarchiver

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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

补充马特的回答,这是绝对正确的。

在我的情况下,我使用的是符合Codable的Struct,为了使其正常工作,我将其编码为Dictionary [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)")
}