- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想使用 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/
我想使用 NSKeyedArchiver 和 NSKeyedUnarchiver 序列化和反序列化我的 GKGraphNode 子类的对象。所以我尝试以下操作: //: Playground - no
我是一名优秀的程序员,十分优秀!