How to use NSUserDefaults to store an array of dictionaries

前端 未结 2 693
悲哀的现实
悲哀的现实 2021-01-28 09:21

Trying to store an array of dictionaries with NSUserDefaults.

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


        
相关标签:
2条回答
  • 2021-01-28 10:07

    Just call the .setObject() method directly from NSUserDefaults()and it should work fine.

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

    0 讨论(0)
  • 2021-01-28 10:22

    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]]
    
    0 讨论(0)
提交回复
热议问题