irkinosor irkinosor - 4 months ago 29
Swift Question

How to use NSUserDefaults with property getter and setter in Swift?

I am trying to save and retrieve a variable in memory directly from its setter and getter property but the getter result in an infinite loop and the app crash with error message :


error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=2, address=0x10049b9a0).
The process has been returned to the state before expression evaluation.


What could be the reason and how to do this properly?

class Task {

var taskList: [String: Double]{

get {

let savedList = memory.dictionaryForKey("SavedTasksList") as? [String: Double] ?? [String: Double]()

return savedList
}

set (tasks){

memory.setObject(tasks, forKey: "SavedTasksList")

}

}
}

JMI JMI
Answer

Do you mean something like this?

class Task {

    var taskList: [String: Double]{

        get {
            return NSUserDefaults.standardUserDefaults().objectForKey("SavedTasksList") as? [String: Double] ?? [String: Double]()
        }

        set {
            let defaults = NSUserDefaults.standardUserDefaults()
            defaults.setObject(newValue, forKey: "SavedTasksList")
            defaults.synchronize()
        }
    }
}

Or in Swift 3:

class Task {

    var taskList: [String: Double]{

        get {
            return UserDefaults.standardUserDefaults().objectForKey("SavedTasksList") as? [String: Double] ?? [String: Double]()
        }

        set {
            let defaults = UserDefaults.standardUserDefaults()
            defaults.setObject(newValue, forKey: "SavedTasksList")
            defaults.synchronize()  
        }
    }
}
Comments