自定义 Class 取消存档在 Cocoa Swift 中为零

Custom Class Unarchive is nil in Cocoa Swift

我正在尝试在我的 macOS 应用程序中将自定义 class 保存和检索到 UserDefaults。 nil 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
    }
}

我能够通过更改来解决此问题:

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

与:

decoder.decodeInteger(forKey: "leftClickCount")