gpt4 book ai didi

swift - 如何实现 NSCoding

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

import Foundation

class C: NSObject, NSCoding {
var n: String = ""

override init() {
super.init()
n = "instance of class C"
}

convenience init(_ name: String) {
self.init()
n = name
}

required init(coder: NSCoder) {
// self.init()
// super.init()
// super.init(coder)
n = coder.decodeObjectForKey("name") as String
}

func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(n, forKey:"name")
}

override var description: String {
get { return "C instance: \(n)" }
}
}

let c = C("Tom")
println(c)
if NSKeyedArchiver.archiveRootObject(c, toFile: "demo") {
println("OK")
}
let c2: C = NSKeyedUnarchiver.unarchiveObjectWithFile("demo") as C

在命令行上编译

xcrun swift coder.swift

调用NSKeyedUnarchiver.unarchiveObjectWithFile失败,崩溃

> xcrun swift coder.swift
C instance: Tom
OK
2014-09-06 10:45:11.925 swift[483:100b] *** Terminating app due to uncaught exception
'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (coder.C)'

我看过各种“工作示例”,但它们似乎不适合我。所有注释行都不起作用或没有帮助。我做错了什么?

最佳答案

我建议打开雷达(bugreport.apple.com)。如果您编译它而不是尝试通过 swift 解释器直接运行它,则效果很好。它可以在 Xcode 中运行。它适用于 Playground 。它与 xcrun -sdk macosx swiftc coder.swift && ./coder 配合使用。唯一不起作用的情况是通过 swift

关于swift - 如何实现 NSCoding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25701476/

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