Stewart Hering
Stewart Hering

Reputation: 304

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?

Upvotes: 5

Views: 2016

Answers (2)

kishikawa katsumi
kishikawa katsumi

Reputation: 10563

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)
}

Upvotes: 5

InkGolem
InkGolem

Reputation: 2762

If you're going to save to user defaults you need to use plist safe objects. So instead of using Float you need to use NSNumber.

Upvotes: 0

Related Questions