I am trying to store an array to NSUserDefaults
and retrieve the array when needed to populate a UITableView
.
Currently I am using:
//store data NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA") NSUserDefaults.standardUserDefaults().synchronize() //retrieve data let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA") myArray = [tabledata!] tableView.reloadData()
But I get
fatal error: unexpectedly found
nil
while unwrapping an Optional value
when trying to load the data. I am not sure if the issue is in the storage or the retrieval. Has anyone been through this before?
You can only store arrays of strings, numbers, Date objects, and Data objects in the user's defaults database. Let's take a look at an example. We access the shared defaults object through the standard class property of the UserDefaults class.
You'll need to convert the object to and from an NSData instance using NSKeyedArchiver and NSKeyedUnarchiver . For example: func savePlaces(){ let placesArray = [Place(lat: 123, lng: 123, name: "hi")] let placesData = NSKeyedArchiver. archivedDataWithRootObject(placesArray) NSUserDefaults.
It appears the limit is the maximum file size for iOS (logically), which is currently 4GB: https://discussions.apple.com/thread/1763096?tstart=0. The precise size of the data is circumscribed by the compiler types (NSData, NSString, etc.) or the files in your asset bundle.
To store the string in the user's defaults database, which is nothing more than a property list or plist, we pass the string to the set(_:forKey:) method of the UserDefaults class. We also need to pass a key as the second argument to the set(_:forKey:) method because we are creating a key-value pair.
From your code I see you are storing some array
// Your code NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
and retrieving a string
//Your code let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
There is probably a type mismatch, You store one type and retrieve another type.
While retrieving either use arrayForKey()
or objectForKey()
see the code below.
let tabledata = NSUserDefaults.standardUserDefaults().arrayForKey("\(identity.text!)listA")
or
let tabledata = NSUserDefaults.standardUserDefaults().objectForKey("\(identity.text!)listA")
If it is an array I would go with First one.
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