我从CloudKit中提取数据以放入数组。
我有3件物品可以提取:Monday
,Tuesday
,Wednesday
我将它们放入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
。
答案 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")
}
}