import UIKit
class Foo: NSObject, NSCoding {
var cx: [Character : Int]
init(cx: [Character : Int]) {
self.cx = cx
}
// MARK: - <NSCoding>
required convenience init(coder aDecoder: NSCoder) {
let cx = aDecoder.decodeObject(forKey: "cxKey") as! [Character : Int]
self.init(cx: cx)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(cx, forKey: "cxKey")
}
}
電話:如何在Swift 3中使用NSCoder對[Character:Int]屬性進行編碼?
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var foo = Foo(cx: ["C": 5, "X": 6])
let encodedData = NSKeyedArchiver.archivedData(withRootObject: foo)
print("encodedData: \(encodedData))")
if let foo1 = NSKeyedUnarchiver.unarchiveObject(with: encodedData) as? Foo {
print("cx = ", foo1.cx)
} else{
print("There is an issue")
}
}
}
Xcode中拋出一個錯誤:***終止應用程序由於未捕獲的異常 'NSInvalidArgumentException',原因是:「 - [_ SwiftValue encodeWithCoder:]:無法識別的選擇發送到實例
你是怎麼稱呼它的? – Rikh
對不起,添加它 – Max