如何使用NSUserDefaults存储字典数组

时间:2016-01-13 17:27:36

标签: arrays swift persistence nsuserdefaults

尝试使用NSUserDefaults存储一系列字典。

var theTasks: [[String:Any]] = [["num":1,"title":"example","colour":"red"]] 

let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(theTasks, forKey: "myTasks")
    defaults.synchronize()

let selected = theTasks[1]

给出错误:

  

无法转换类型' [[String:Any]]'的值预期的类型' AnyObject的参数?'

2 个答案:

答案 0 :(得分:1)

Swift 3.x

在Swift 3中它已经改变所以现在它需要保存为[Any]任何数组并使用UserDefaults数组(forKey :)方法来加载它:

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

您只需将其另存为AnyObject数组并使用NSUserDefaults方法arrayForKey加载它:

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)
}

您还可以使用getter和setter创建一个计算属性,以便为您完成幕后的所有工作,如下所示:

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]]

答案 1 :(得分:-1)

直接从.setObject()调用NSUserDefaults()方法,它应该可以正常工作。

NSUserDefaults().setObject(theTasks, forKey: "myTasks")