Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving to User Defaults in Swift

I am currently trying to save an array to the user defaults.

Here is my code:

//where things will be stored
let defaults = NSUserDefaults.standardUserDefaults()
var taskNames = [String]()
var taskPriorities = [Float]()

//this is the function that saves tasks
func saveTask() {
    println(taskNames)
    println(taskPriorities)
    defaults.setObject(taskNames, forKey: "taskName")
    defaults.setObject(taskPriorities, forKey: "taskPriorities")
    defaults.synchronize()
}

//this is the function that loads tasks
func loadTasks() {
    var taskNamesLoad = defaults.dataForKey("taskName")

    println(defaults.dataForKey("taskName"))
    println(taskNamesLoad)
}

When I call the function to load the data (after saving some data with the other function of course) the output to the Console is nil and there is no data saved in the user defaults. How can I fix this?

like image 854
Stewart Hering Avatar asked Mar 24 '15 16:03

Stewart Hering


Video Answer


1 Answers

You should use arrayForKey or objectForKey instead dataForKey. Because you store the Array object, not NSData.

Like below:

func loadTasks() {
    var taskNamesLoad = defaults.arrayForKey("taskName")

    println(defaults.arrayForKey("taskName"))
    println(taskNamesLoad)
}
like image 146
kishikawa katsumi Avatar answered Oct 17 '22 10:10

kishikawa katsumi