gpt4 book ai didi

swift - 使用 NSKeyedUnarchiver 反序列化 GKGraphNode 的子类

转载 作者:行者123 更新时间:2023-11-30 11:40:16 25 4
gpt4 key购买 nike

我想使用 NSKeyedArchiver 和 NSKeyedUnarchiver 序列化和反序列化我的 GKGraphNode 子类的对象。所以我尝试以下操作:

//: Playground - noun: a place where people can play

import GameplayKit

class MyGraphNode: GKGraphNode {
static let textCodingKey = "TextCodingKey"

let text: String

override convenience init() {
self.init(text: "Default Text")
}

init(text: String) {
self.text = text

super.init()
}

required init?(coder aDecoder: NSCoder) {
text = aDecoder.decodeObject(forKey: MyGraphNode.textCodingKey) as! String

super.init(coder: aDecoder)
}

override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)

aCoder.encode(text, forKey: MyGraphNode.textCodingKey)
}
}

let text = "Test Text"

let graphNode = MyGraphNode(text: text)

let data = NSKeyedArchiver.archivedData(withRootObject: graphNode)

if let unarchivedGraphNode = NSKeyedUnarchiver.unarchiveObject(with: data) as? MyGraphNode {
print("Text: \(unarchivedGraphNode.text)")
}

不幸的是,该示例仅打印默认文本,而不打印预期的测试文本:

Text: Default Text

首先,我省略了便利初始化程序。但在这种情况下,它因以下错误而崩溃:

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0). The process has been left at thepoint where it was interrupted, use "thread return -x" to return tothe state before expression evaluation.

GKGraphNodeSubclass.playground: 5: 7: Fatal error: Use ofunimplemented initializer 'init()' for class'__lldb_expr_58.MyGraphNode'

谁能解释一下为什么在反序列化过程中测试文本被忽略?
或者为什么我必须添加便利初始化程序?

最佳答案

我在 Apple Developer Forum 中获得了帮助:

The "text" property is ending up being reset by "super.init(coder: aDecoder)", presumably because that calls "init()" internally, and that ends up at your convenience "init ()". This would be illegal in Swift, but it's legal in Obj-C, which doesn't have the same strict initialization rules.

The solution is to initialize "text" after the super.init(coder:), rather than before. This means you can't use a "let" property

为了修复我的示例,我更改了变量声明和 NSCoding 初始值设定项,如下所示:

var text: String!

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

text = aDecoder.decodeObject(forKey: MyGraphNode.textCodingKey) as! String
}

关于swift - 使用 NSKeyedUnarchiver 反序列化 GKGraphNode 的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49353225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com