第二个数组项被删除

时间:2016-03-15 00:04:20

标签: ios swift nsarray nsuserdefaults

我从CloudKit中提取数据以放入数组。

我有3件物品可以提取:MondayTuesdayWednesday

我将它们放入existingArray,但是当我运行应用时,我得到:["Monday", "Tuesday"],然后当它第二次运行时我得到["Monday", "Wednesday"],我可以&#39 ;弄清楚原因?

    for days in results! {
        let nD = DayClass()
        nD.dayOfTheWeek = days[“D”] as! String
        let defaults = NSUserDefaults.standardUserDefaults()
            if var existingArr = defaults.arrayForKey("D") as? [String] {
                if existingArr.contains(days["D"] as! String) == false {
                    existingArr.append(nd.dayOfTheWeek)
                }
            } else {
                defaults.setObject([nD.dayOfTheWeek], forKey: "D")
            }
        }

修改:如果我在追加后添加defaults.setObject([nD.dayOfTheWeek], forKey: "D"),则existingArray变为["Monday", "Tuesday"],然后["Tuesday", "Wednesday"]。我无法将所有3个项目保留在existingArray

1 个答案:

答案 0 :(得分:0)

您需要在existingArr之后将append恢复为默认值。沿着:

for days in results! {
    let nD = DayClass()
    nD.dayOfTheWeek = days[“D”] as! String
    let defaults = NSUserDefaults.standardUserDefaults()
        if var existingArr = defaults.arrayForKey("D") as? [String] {
            if existingArr.contains(days["D"] as! String) == false {
                existingArr.append(nd.dayOfTheWeek)
                defaults.setObject(existingArr, forKey: "D")
            }
        } else {
            defaults.setObject([nD.dayOfTheWeek], forKey: "D")
        }
    }