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 store array of values in NSUserDefaults in swift
let array = [1, 2, 9, 3, 22]
UserDefaults.standard.set(array, forKey: "studentIDs")
//get id's array from user defaults
let studentIdsArray = UserDefaults.standard.array(forKey: "studentIDs")
There are plenty of questions/solutions, here is one:
how to save and read array of array in NSUserdefaults in swift?
But as another user said, please take a look at the official documentation: https://developer.apple.com/documentation/foundation/userdefaults
Swift store array with UserDefaults
The reason of the error is that the compiler cannot infer the type of the array.
Spend an extra line to read, change and write the data, for example:
let defaults = UserDefaults.standard
var seenPosts : [Int]
if let actual = defaults.array(forKey: "seen_posts") as? [Int] {
seenPosts = actual
} else {
seenPosts = [Int]()
}
seenPosts.insert(321, at: 0)
defaults.set(seenPosts, forKey: "seen_posts")
or if the default key seen_posts
is registered – as recommended – simpler
let defaults = UserDefaults.standard
var seenPosts = defaults.array(forKey: "seen_posts") as! [Int]
seenPosts.insert(321, at: 0)
defaults.set(seenPosts, forKey: "seen_posts")
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…
}
}
}
How to use NSUserDefaults to store an array of dictionaries
Swift 3.x
In Swift 3 it has changed so now it needs to be saved as [Any]
Any Array and use UserDefaults array(forKey:) method to load it:
let theTasks: [Any] = [["num": 1, "title": "example", "colour": "red"]]
UserDefaults.standard.set(theTasks, forKey: "myTasks")
if let loadedTasks = UserDefaults.standard.array(forKey: "myTasks") as? [[String: Any]] {
print(loadedTasks)
}
var theTasks: [[String: Any]] {
get {
return UserDefaults.standard.array(forKey: "myTasks") as? [[String: Any]] ?? []
}
set {
UserDefaults.standard.set(newValue as [Any], forKey: "myTasks")
}
}
Swift 2.x
You just need to save it as a AnyObject
array and use NSUserDefaults
method arrayForKey
to load it:
let theTasks: [AnyObject] = [["num": 1, "title": "example", "colour": "red"]]
NSUserDefaults.standardUserDefaults().setObject(theTasks, forKey: "myTasks")
if let loadedTasks = NSUserDefaults.standardUserDefaults().arrayForKey("myTasks") as? [[String: AnyObject]] {
print(loadedTasks)
}
You can also create a computed property with a getter and a setter to do all the work behind the scenes for you as follow:
var theTasks: [[String: AnyObject]] {
get {
return NSUserDefaults.standardUserDefaults().arrayForKey("myTasks") as? [[String: AnyObject]] ?? []
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue as [AnyObject], forKey: "myTasks")
}
}
print(theTasks) // [["title": example, "colour": red, "num": 1]]
theTasks[0]["title"] = "another example"
print(theTasks) // [["title": another example, "colour": red, "num": 1]]
How to use NSUserDefaults to store an array of custom classes in Swift?
Your Person class should look like this:
Swift 3:
class Person : NSObject, NSCoding{
// Person dictionary variable
var name: String?
var age: String?
var html_url: String?
init(json: NSDictionary) { // Dictionary object
self.name = json["name"] as? String
self.age = json["age"] as? String
self.html_url = json["html_url"] as? String // Location of the JSON file
}
required init?(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObjectForKey("name") as? String;
self.age = aDecoder.decodeObjectForKey("age") as? String;
self.html_url = aDecoder.decodeObjectForKey("html") as? String;
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.name, forKey: "name");
aCoder.encodeObject(self.age, forKey: "age");
aCoder.encodeObject(self.html_url, forKey: "html");
}
}
And here you have an example of saving and retrieving the array from NSUserDefaults:
let p = Person()
p.name = "person1"
p.age = "12"
p.html_url = "www.google.ro"
let p2 = Person()
p2.name = "person2"
p2.age = "11"
p2.html_url = "www.google.ro"
let array = [p, p2]
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValue(NSKeyedArchiver.archivedDataWithRootObject(array), forKey: "persons")
userDefaults.synchronize()
let array : [Person]
array = NSKeyedUnarchiver.unarchiveObjectWithData(userDefaults.objectForKey("persons") as! NSData) as! [Person]
print("\(array[0].name)\(array[1].name)")
Swift 4:
class Person : NSObject, NSCoding{
// Person dictionary variable
var name: String?
var age: String?
var html_url: String?
init(json: NSDictionary) { // Dictionary object
self.name = json["name"] as? String
self.age = json["age"] as? String
self.html_url = json["html_url"] as? String // Location of the JSON file
}
required init?(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey: "name") as? String;
self.age = aDecoder.decodeObject(forKey: "age") as? String;
self.html_url = aDecoder.decodeObject(forKey: "html") as? String;
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name");
aCoder.encode(self.age, forKey: "age");
aCoder.encode(self.html_url, forKey: "html");
}
}
Related Topics
iOS Pod Install Gcm and Pnchartswift
Xcode 12.5 Missing Entitlement Com.Apple.Developer.Associated-Appclip-App-Identifiers
Avmutablevideocomposition Output Video Shrinked
How Parsing Firebase Fdatasnapshot JSON Data in Swift
How to Give Cornerradius for Uibezierpath
Uitableview Height Does Not Change Dynamically in Swift iOS
iOS - How to Make the Uiscrolling Indicator Height Same for Any Number of Data
Converting an Existing Project into Customizable Framework
How to Delete an Image from Photolibrary After I Pick It Up Using Uiimagepickercontroller
Pausing Spritekit Game Using Appdelegate in iOS8
Items in File Provider Extension for iOS 11
How to Use Gadbannerviewdelegate to Perform Action on Adviewdidreceivead
Rotate Image in Share Extension
How to Update Constraints Programmatically
Design Pattern for Realm Database Swift 3.1 - Singleton