Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFTimer encodeWithCoder:]

107 views Asked by At

Is there anyway that i can save an NSTimer to UserDefaults and NSKeyedUnarchiver and use it later ? Below is my example code

  static var timerDictionary : [String:Timer]? {
    get{
        let outData = UserDefaults.standard.data(forKey: "timerDictionary") ?? Data()
        if let dict = NSKeyedUnarchiver.unarchiveObject(with: outData) as? [String:Timer]?{
            
            return dict
        }else{
            return [:]
        }
        
    }
    set{
        let data = NSKeyedArchiver.archivedData(withRootObject: newValue ?? [:])
        UserDefaults.standard.set(data, forKey: "timerDictionary")
    }
}

However my app crashes with 'NSInvalidArgumentException', reason: '-[__NSCFTimer encodeWithCoder:].

1

There are 1 answers

1
efess On

if you want to continue your timer when app becomes active again, the better approach will be to save yours timer last state (countdown or tick) and create new timer instance from saved state