如果对象已成功解码,则 NSCoder 无法再次解码对象

NSCoder fails to decode object a second time if the object was already successfully decoded

提问人:Warpling 提问时间:9/29/2023 更新时间:9/29/2023 访问量:13

问:

我正在对一些对象进行编码/解码,并且在测试多种取消存档对象的方法的过程中,注意到删除一些打印语句改变了解码器行为。删除对象时,NSCoder 对象是否会被“丢弃”?这是预期行为吗?NSSecureCoding

以前

例如,This 存储在 .如果我尝试以 3 种不同的方式对其进行解码并打印输出,它将如下所示。FakeObject"FakeObjectKey"

print("FakeObject exists? \(coder.containsValue(forKey: "FakeObjectKey"))")
print("FakeObject insecure? \(coder.decodeObject(forKey: "FakeObjectKey"))")
print("FakeObject secure? \(coder.decodeObject(of: FakeObject.self, forKey: "FakeObjectKey"))")

输出似乎有效,然后失败两次:

FakeStorekeeper exists? true
FakeStorekeeper insecure? nil
FakeStorekeeper secure? nil

但是,如果我注释掉前两个 print 语句,您可以看到第三种方法实际上成功了:

// print("FakeObject exists? \(coder.containsValue(forKey: "FakeObjectKey"))")
// print("FakeObject insecure? \(coder.decodeObject(forKey: "FakeObjectKey"))")
print("FakeObject secure? \(coder.decodeObject(of: FakeObject.self, forKey: "FakeObjectKey"))")

输出更改:

FakeObject secure? Optional(< FakeObject: 0x60000022a180>)
iOS nskeyedunarchiver nssecurecoding

评论


答:

1赞 Warpling 9/29/2023 #1

显然,当您从中解码对象时,会被丢弃,并且后续对解码同一对象/键的调用将静默失败。据我所知,这是未定义的行为。在外面要小心。NSCoder