Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Swift) Storing and retrieving Array to NSUserDefaults

Tags:

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?

like image 828
William Larson Avatar asked May 08 '15 07:05

William Larson


People also ask

Can I store array in UserDefaults Swift?

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.

How do I save an array of objects in Swift?

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.

How much data can you store in 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.

How do you save a Userdefault string in Swift?

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.


1 Answers

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.

like image 125
Vivek Molkar Avatar answered Oct 21 '22 09:10

Vivek Molkar