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?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With