问题
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()
}
回答1:
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?
回答2:
"[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
}
回答3:
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)
}
回答4:
In Swift-3, the following way to Saving array with UserDefaults :
let userDefaults = UserDefaults.standard
userDefaults.set(arrayOfname, forKey:"Keyname")
userDefaults.synchronize()
来源:https://stackoverflow.com/questions/41441446/saving-array-with-userdefaults