how to save and read array of array in NSUserdefaults in swift?
The question reads "array of array" but I think most people probably come here just wanting to know how to save an array to UserDefaults
. For those people I will add a few common examples.
String array
Save array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")
Retrieve array
let defaults = UserDefaults.standard
let myarray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]()
Int array
Save array
let array = [15, 33, 36, 723, 77, 4]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedIntArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedIntArray") as? [Int] ?? [Int]()
Bool array
Save array
let array = [true, true, false, true, false]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedBoolArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedBoolArray") as? [Bool] ?? [Bool]()
Date array
Save array
let array = [Date(), Date(), Date(), Date()]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedDateArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedDateArray") as? [Date] ?? [Date]()
Object array
Custom objects (and consequently arrays of objects) take a little more work to save to UserDefaults
. See the following links for how to do it.
- Save custom objects into NSUserDefaults
- Docs for saving color to UserDefaults
- Attempt to set a non-property-list object as an NSUserDefaults
Notes
- The nil coalescing operator (
??
) allows you to return the saved array or an empty array without crashing. It means that if the object returns nil, then the value following the??
operator will be used instead. - As you can see, the basic setup was the same for
Int
,Bool
, andDate
. I also tested it withDouble
. As far as I know, anything that you can save in a property list will work like this.
(Swift) Storing and retrieving Array to NSUserDefaults
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.
How to save an array of objects to NSUserDefault with swift?
From the Property List Programming Guide:
If a property-list object is a container (that is, an array or dictionary), all objects contained within it must also be property-list objects. If an array or dictionary contains objects that are not property-list objects, then you cannot save and restore the hierarchy of data using the various property-list methods and functions.
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.standardUserDefaults().setObject(placesData, forKey: "places")
}
func loadPlaces(){
let placesData = NSUserDefaults.standardUserDefaults().objectForKey("places") as? NSData
if let placesData = placesData {
let placesArray = NSKeyedUnarchiver.unarchiveObjectWithData(placesData) as? [Place]
if let placesArray = placesArray {
// do something…
}
}
}
Saving an array of NSURL to NSUserDefaults
when saving, save the absolute strings of the urls. when loading use NSURL(URLString:) to make the strings into urls again
import UIKit
class ViewController: UIViewController {
var urlsArray : [NSURL]?
func load () {
var urls : [NSURL] = []
let stringsArray = NSUserDefaults.standardUserDefaults().objectForKey("stringsArray") as [String]?
if let array = stringsArray {
for string in array {
var url = NSURL(string: string)
urls.append(url!) //no null check
}
}
self.urlsArray = urls
}
func save () {
var strings : [String] = []
if let array = self.urlsArray {
for url in array {
var string = url.absoluteString
strings.append(string!) ////no null check
}
}
NSUserDefaults.standardUserDefaults().setObject(strings, forKey: "stringsArray")
}
}
saving can be reduced with KVC.
func save () {
var strings : [String] = []
if let array = self.urlsArray as NSArray? {
strings = array.valueForKeyPath("absoluteStrings")
}
NSUserDefaults.standardUserDefaults().setObject(strings, forKey: "stringsArray")
}
Related Topics
Since Xcode 8 and iOS10, Views Are Not Sized Properly on Viewdidlayoutsubviews
How to Create a Simple Checkbox in iOS
Is There an iPhone Se Simulator for Xcode 11, iOS 13
-Canopenurl: Failed for Url: "Fbauth2:/" (Osstatus Error -10814.)"
Alternative iOS Layouts for Portrait and Landscape Using Just One .Xib File
iOS 5.1 with Xcode 4.2 and Retina in iPad 3
What Is a "Delegate" in Objective C's iPhone Development
Uibezierpath Triangle with Rounded Edges
Does This App Use the Advertising Identifier (IDFA)? - Admob 6.8.0
Core Data Multi Thread Application
How to Disable Floating Headers in Uitableview with Uitableviewstyleplain
Analysing Assets.Car File in iOS
Why Is Uicollectionviewcell's Outlet Nil
How to Check If a File Exists in Documents Folder
What Exactly Can Corebluetooth Applications Do Whilst in the Background
Swift Get String Between 2 Strings in a String
Ios: Frame.Size.Width/2 Doesn't Produce a Circle on Every Device
Add a Running Countup Display Timer to an iOS App, Like the Clock Stopwatch