NSCoding和Codable可以共存吗?



在测试新的Codable如何与NSCoding交互时,我整理了一个游乐场测试,涉及使用包含Codable结构的类的NSCoding。要白

struct Unward: Codable {
var id: Int
var job: String
}
class Akward: NSObject, NSCoding {
var name: String
var more: Unward
init(name: String, more: Unward) {
self.name = name
self.more = more
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(more, forKey: "more")
}
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
more = aDecoder.decodeObject(forKey: "more") as? Unward ?? Unward(id: -1, job: "unk")
super.init()
}
}
var upone = Unward(id: 12, job: "testing")
var adone = Akward(name: "Adrian", more: upone)

以上内容场接受,不会产生任何编译器错误。

但是,如果我尝试保存adone,如下所示:

let encodeit = NSKeyedArchiver.archivedData(withRootObject: adone)

操场立即崩溃并显示错误:

错误:执行中断,原因:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0(。

为什么? 有没有办法让 NSCoding 类包含可编码的结构?

现有的答案并没有真正解决互操作的问题,而是展示了如何从NSCoding迁移到Codable

我有一个用例,这不是一个选项,我确实需要从Codable上下文中使用NSCoding。如果您很好奇:我需要在我的Mac应用程序的XPC服务之间发送模型,并且这些模型包含NSImage。我本可以制作一堆序列化/反序列化图像的 DTO,但这将是很多样板。此外,这是属性包装器的完美用例。

这是我想出的属性包装器:

@propertyWrapper
struct CodableViaNSCoding<T: NSObject & NSCoding>: Codable {
struct FailedToUnarchive: Error { }
let wrappedValue: T
init(wrappedValue: T) { self.wrappedValue = wrappedValue }
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let data = try container.decode(Data.self)
let unarchiver = try NSKeyedUnarchiver(forReadingFrom: data)
unarchiver.requiresSecureCoding = Self.wrappedValueSupportsSecureCoding
guard let wrappedValue = T(coder: unarchiver) else {
throw FailedToUnarchive()
}
unarchiver.finishDecoding()
self.init(wrappedValue: wrappedValue)
}
func encode(to encoder: Encoder) throws {
let archiver = NSKeyedArchiver(requiringSecureCoding: Self.wrappedValueSupportsSecureCoding)
wrappedValue.encode(with: archiver)
archiver.finishEncoding()
let data = archiver.encodedData
var container = encoder.singleValueContainer()
try container.encode(data)
}
private static var wrappedValueSupportsSecureCoding: Bool {
(T.self as? NSSecureCoding.Type)?.supportsSecureCoding ?? false
}
}

这是我为它编写的简单测试:

import Quick
import Nimble
import Foundation
@objc(FooTests_SampleNSCodingClass)
private class SampleNSCodingClass: NSObject, NSCoding {
let a, b, c: Int
init(a: Int, b: Int, c: Int) {
self.a = a
self.b = b
self.c = c
}
required convenience init?(coder: NSCoder) {
self.init(
a: coder.decodeInteger(forKey: "a"),
b: coder.decodeInteger(forKey: "b"),
c: coder.decodeInteger(forKey: "c")
)
}
func encode(with coder: NSCoder) {
coder.encode(a, forKey: "a")
coder.encode(b, forKey: "b")
coder.encode(c, forKey: "c")
}
}
@objc(FooTests_SampleNSSecureCodingClass)
private class SampleNSSecureCodingClass: SampleNSCodingClass, NSSecureCoding {
static var supportsSecureCoding: Bool { true }
}
private struct S<T: NSObject & NSCoding>: Codable {
@CodableViaNSCoding
var sampleNSCodingObject: T
}
class CodableViaNSCodingSpec: QuickSpec {
override func spec() {
context("Used with a NSCoding value") {
let input = S(sampleNSCodingObject: SampleNSCodingClass(a: 123, b: 456, c: 789))
it("round-trips correctly") {
let encoded = try JSONEncoder().encode(input)
let result = try JSONDecoder().decode(S<SampleNSCodingClass>.self, from: encoded)
expect(result.sampleNSCodingObject.a) == 123
expect(result.sampleNSCodingObject.b) == 456
expect(result.sampleNSCodingObject.c) == 789
}
}
context("Used with a NSSecureCoding value") {
let input = S(sampleNSCodingObject: SampleNSSecureCodingClass(a: 123, b: 456, c: 789))
it("round-trips correctly") {
let encoded = try JSONEncoder().encode(input)
let result = try JSONDecoder().decode(S<SampleNSSecureCodingClass>.self, from: encoded)
expect(result.sampleNSCodingObject.a) == 123
expect(result.sampleNSCodingObject.b) == 456
expect(result.sampleNSCodingObject.c) == 789
}
}
}
}

一些注意事项:

  1. 如果您需要走另一条路(在NSCoding存档中嵌入Codable对象(,您可以使用添加到NSCoder/NSDecoder的现有方法

  2. 这是为每个对象创建一个新的存档。除了在编码/解码过程中添加相当多的对象分配外,它还可能会使结果膨胀(在我的测试中,空存档大约为 220 字节(。

  3. 从根本上说,CodableNSCoding更受限制。Codable的实现方式只能处理具有值语义的对象。结果:

    • 具有别名(对同一对象的多个引用(的对象图将导致对象图重复
    • 带有循环的对象图永远无法解码(会有无限递归(

    这意味着您无法真正围绕NSCoder/NSCoder类(如NSKeyedArchiver/NSKeyedUnarchiver(制作Encoder/Decoder包装器,而无需放入一堆簿记来检测这些场景并fatalError。(这也意味着您不能支持存档/取消存档任何常规NSCoding对象,而只能支持那些没有别名或周期的对象(。这就是为什么我选择了"制作一个独立的存档并将其编码为Data"的appoach。

您得到的实际错误是:

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

这是来自以下行:

aCoder.encode(more, forKey: "more")

问题的原因是more(类型Unward(不符合NSCoding。但是斯威夫特struct不符合NSCoding。您需要将Unward更改为除了符合NSCoding之外还扩展NSObject的类。这些都不会影响符合Codable的能力。

以下是您更新的课程:

class Unward: NSObject, Codable, NSCoding {
var id: Int
var job: String
init(id: Int, job: String) {
self.id = id
self.job = job
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(job, forKey: "job")
}
required init?(coder aDecoder: NSCoder) {
id = aDecoder.decodeInteger(forKey: "id")
job = aDecoder.decodeObject(forKey: "job") as? String ?? ""
}
}
class Akward: NSObject, Codable, NSCoding {
var name: String
var more: Unward
init(name: String, more: Unward) {
self.name = name
self.more = more
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(more, forKey: "more")
}
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
more = aDecoder.decodeObject(forKey: "more") as? Unward ?? Unward(id: -1, job: "unk")
}
}

以及您的测试值:

var upone = Unward(id: 12, job: "testing")
var adone = Akward(name: "Adrian", more: upone)

您现在可以归档和取消归档:

let encodeit = NSKeyedArchiver.archivedData(withRootObject: adone)
let redone = NSKeyedUnarchiver.unarchiveObject(with: encodeit) as! Akward

您可以编码和解码:

let enc = try! JSONEncoder().encode(adone)
let dec = try! JSONDecoder().decode(Akward.self, from: enc)

相关内容

  • 没有找到相关文章

最新更新