(Swift) Storing and retrieving Array to NSUserDefaults

前端 未结 7 978
别跟我提以往
别跟我提以往 2020-11-30 05:43

I am trying to store an array to NSUserDefaults and retrieve the array when needed to populate a UITableView.

Currently I am using:

<
7条回答
  •  执笔经年
    2020-11-30 06:25

    This has been changed in swift 3. Note that this works with device but not playground or simulator

    //store the array
    let array = ["horse", "cow", "camel", "sheep", "goat"]
    
    let defaults = UserDefaults.standard
    
    defaults.setValue(array, forKey: "history")
    
    defaults.synchronize()
    
    //Retrieve the array
    if((UserDefaults.standard.array(forKey: "history")) != nil){
        let historyWords = (UserDefaults.standard.array(forKey: "history") as? [String])!
        print(historyWords)
    }
    

提交回复
热议问题