0

我正在尝试在我的 macOS 应用程序中将自定义类保存并检索到 UserDefaults。我的newData为零

class countClass: NSObject, NSCoding {
    var leftClickCount : Int = 0

    init(leftClickCount: Int) {
        self.leftClickCount = leftClickCount
        super.init()
    }

    func encode(with coder: NSCoder) {
        coder.encode(self.leftClickCount, forKey: "leftClickCount")
    }

    required convenience init?(coder decoder: NSCoder) {
        guard let leftClickCount = decoder.decodeObject(forKey: "leftClickCount") as? Int
            else {
            return nil
        }
        self.init(
            leftClickCount: leftClickCount
        )
    }
}

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let leftC = countClass(leftClickCount: 25)
        let ud = UserDefaults.standard
        let archivedData = NSKeyedArchiver.archivedData(withRootObject: leftC)
        ud.set(archivedData, forKey: "data")
        ud.synchronize()
        let tempData = ud.object(forKey: "data") as! Data
        let newData = NSKeyedUnarchiver.unarchiveObject(with: tempData) as! countClass // Getting nil here
    }
}
4

1 回答 1

0

我可以通过更改来解决这个问题:

decoder.decodeObject(forKey: "leftClickCount") as? Int

和:

decoder.decodeInteger(forKey: "leftClickCount")

于 2017-02-06T22:06:11.213 回答