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're going to save to user defaults you need to use plist safe objects. So instead of using Float
you need to use NSNumber
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.