Kashif Kashif - 4 years ago 86
Swift Question

Custom Class Unarchive is nil in Cocoa Swift

I am trying to save and retrieve a custom class to UserDefaults in my macOS app. I am getting nil for 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
}
}

Answer Source

I was able to fix this problem by changing from:

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

with:

decoder.decodeInteger(forKey: "leftClickCount")

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download