简体   繁体   English

使用UserDefaults保存数组

[英]Saving array with UserDefaults

Is this the right way to save array of dictionaries in tableView using UserDefaults in Swift 3? 这是在Swift 3中使用UserDefaults在tableView中保存字典数组的正确方法吗? var arrNotes = [String:String] var arrNotes = [String:String]

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

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? 您是否以同样的方式得到对象?

"[String: String]" Means a dictionary where the keys and the values are Strings. “ [[String:String]””表示其中键和值是String的字典。

"[[String: String]]" Means an array that contains dictionaries where the keys and values are strings. “ [[[String:String]]”表示包含键和值是字符串的字典的数组。

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 将数组添加到userDefaults

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

userDefaults.synchronize();

get the array of dictionaries from the userdefaults 从userdefaults获取字典数组

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

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. 从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)

} }

In Swift-3, the following way to Saving array with UserDefaults : 在Swift-3中,通过以下方式使用UserDefaults保存数组:

let userDefaults = UserDefaults.standard

userDefaults.set(arrayOfname, forKey:"Keyname")
userDefaults.synchronize()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM