在NSUserDefaults Swift中附加一个数组

时间:2015-07-05 00:40:53

标签: ios swift nsuserdefaults

所以我想在NSUserDefaults中附加一个数组,而不是保存一个全新的数组。问题是我希望数组是特定类型用户交互的记录历史记录,因此我需要在NSUserDefaults中附加现有数组,而不是覆盖它。

即不:

var data = [String]()
var questionsAsked = [String]()

func storeData() {

    let defaults = NSUserDefaults.standardUserDefaults()

    defaults.setObject(questionsAsked, forKey: "questionsAsked")
    defaults.setObject(data, forKey: "data")

    var storedQuestionsAsked = defaults.objectForKey("questionsAsked") as? [String] ?? [String]()

    var storedData = defaults.objectForKey("data") as? [String] ?? [String]()

}

数组基于我的模态,并且通过在该模态的ViewController中附加该数组来进行追加

我试过调用这样的函数,但这只是调用一个空数组,因为它永远不会被重新保存到NSUserDefaults:

func updateQuestionsAsked(questionAsked: String, answerGiven: String) {

    let defaults = NSUserDefaults.standardUserDefaults()

    defaults.setObject([String](), forKey: "questionsAsked")
    defaults.setObject([String](), forKey: "data")

    var storedQuestionsAsked = defaults.objectForKey("questionsAsked") as? [String] ?? [String]()
    var storedData = defaults.objectForKey("data") as? [String] ?? [String]()

    storedData.append(questionAsked)
    storedQuestionsAsked.append(answerGiven)

    NSUserDefaults.standardUserDefaults().synchronize()
}

我缺少某种同步的东西吗?我确信这非常简单,但我只是在做什么。谢谢!

1 个答案:

答案 0 :(得分:4)

你正在设置密钥“questionsAsked”&的空数据。 “数据”,

func updateQuestionsAsked(questionAsked: String, answerGiven: String) {

    let defaults = NSUserDefaults.standardUserDefaults()

    //remove this
    //defaults.setObject([String](), forKey: "questionsAsked")
    //defaults.setObject([String](), forKey: "data")

    var storedQuestionsAsked = defaults.objectForKey("questionsAsked") as? [String] ?? [String]()
    var storedData = defaults.objectForKey("data") as? [String] ?? [String]()

    storedData.append(questionAsked)
    storedQuestionsAsked.append(answerGiven)

    // then update whats in the `NSUserDefault`
    defaults.setObject(questionsAsked, forKey: "questionsAsked")
    defaults.setObject(data, forKey: "data")

    // call this after you update
    defaults.synchronize()
}

另一个可能是你未能在这里设置对象......

func storeData() {

    let defaults = NSUserDefaults.standardUserDefaults()

    defaults.setObject(questionsAsked, forKey: "questionsAsked")
    defaults.setObject(data, forKey: "data")

    // call this after setting Objects
    //--
    defaults.synchronize()
    //--

    ...
}