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

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
leftClickCount: leftClickCount

class ViewController: NSViewController {

override func viewDidLoad() {

let leftC = countClass(leftClickCount: 25)
let ud = UserDefaults.standard
let archivedData = NSKeyedArchiver.archivedData(withRootObject: leftC)
ud.set(archivedData, forKey: "data")
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


decoder.decodeInteger(forKey: "leftClickCount")

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