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)'
我看过各种“工作实例”,但它们似乎对我不起作用。没有评论的行有效或有帮助。我做错了什么?
答案 0 :(得分:1)
我建议打开雷达(bugreport.apple.com)。如果您编译它而不是尝试直接通过swift
解释器运行它,这可以正常工作。它适用于Xcode。它适用于游乐场。它适用于xcrun -sdk macosx swiftc coder.swift && ./coder
。它不起作用的唯一情况是swift
。