Saving array with UserDefaults

4.2k views Asked by At

Is this the right way to save array of dictionaries in tableView using UserDefaults in Swift 3? var arrNotes = [String:String]

func saveNotesArray () {
    UserDefaults.standard.set(arrNotes, forKey: "notes")
    UserDefaults.standard.synchronize()
}
4

There are 4 answers

3
Peep On

"[String: String]" Means a dictionary where the keys and the values are Strings.

"[[String: String]]" Means an array that contains dictionaries where the keys and values are strings.

create a dictionary of string and an array to hold them

let dictionary: [String: String] = ["keyOne" : "valueOne", "keyTwo": "valueTwo"]
let arrayWithDictionaryOfStrings: [[String: String]] = [dictionary]

add the array to userDefaults

let userDefaults = UserDefaults.standard
userDefaults.set(arrayWithDictionaryOfStrings, forKey: "arrayWithDictionaryOfStrings")

userDefaults.synchronize();

get the array of dictionaries from the userdefaults

if let fetchedArrayWithDictionaryOfStrings: [[String: String]] = (userDefaults.object(forKey: "arrayWithDictionaryOfStrings") as? [[String: String]]) {
    // handle fetchedArrayWithDictionaryOfStrings
}
0
Dheeraj D On

Use this function to get your notes:

 func saveNotesArray () {
       var notes = UserDefaults.standard.object(forKey: "notes") as?   [String:String]
}

Are you getting object in same way?

1
Bhushan Rana On

In Swift-3, the following way to Saving array with UserDefaults :

let userDefaults = UserDefaults.standard

userDefaults.set(arrayOfname, forKey:"Keyname")
userDefaults.synchronize()
0
Abu Ul Hassan On

your should do it like This For Saving

let placesData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(arrNotes, forKey: "notes")

To Retrieved array from NSUserDefault.

let placesData = UserDefaults.standard.object(forKey: "notes") as? NSData

if let placesData = placesData {
    let arrNotes = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? NSMutableArray
    print(arrNotes)

}