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)'我看过各种各样的“工作例子”,但它们似乎不适合我。所有评论行都不起作用,也没有帮助。我做错了什么?
发布于 2014-09-06 15:18:07
我建议打开雷达(bugreport.apple.com)。如果您编译它,而不是试图通过swift解释器直接运行它,这是很好的。它在Xcode中工作。它在操场上工作。它适用于xcrun -sdk macosx swiftc coder.swift && ./coder。它不起作用的唯一情况是通过swift。
https://stackoverflow.com/questions/25701476
复制相似问题