有没有办法为NSUserDefaults
中的同一个密钥保存多个值?我似乎只保存最后一个值,即使我有“Day”键的多个值。
Day
:
for days in results! {
let nD = DayClass()
nD.dayOfTheWeek = days[“D”] as! String
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(nD.dayOfTheWeek, forKey: “Day”)
}
我尝试过创建一个数组作为一种可能的解决方案,但是当我在控制台中记录它时,我仍然只得到最后一个值:
var emptyArray = [String]()
emptyArray.append(dayOfTheWeek)
print("Array: \(emptyArray)")
print("ArrayCount: \(emptyArray.count)")
答案 0 :(得分:1)
你可以这样做。首先检查prefs中是否已有Day数组。如果是这样,那么将新的dayOfTheWeek添加到该数组并存储它。否则创建一个新的并存储它。
for days in results! {
let dayOfTheWeek = days["D"] as! String
//check if there is already an existing Day array in prefs
if var existingArr = NSUserDefaults.standardUserDefaults().arrayForKey("Day") as? [String] {
//if so append the new value to that array and store it
if existingArr.contains(dayOfTheWeek) == false {
existingArr.append(dayOfTheWeek)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(existingArr, forKey: "Day")
defaults.synchronize()
}
} else {
//create a new array and store it
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject([dayOfTheWeek], forKey: "Day")
defaults.synchronize()
}
}
答案 1 :(得分:0)
var food: [String]
{
get {
if let returnValue =
NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String] {
return returnValue
} else {
return ["muesli", "banana"] //Default value
}
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "food")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
override func viewDidLoad() {
super.viewDidLoad()
print(food) // prints: ["muesli", "banana"] (at first launch)
food = ["cake"]
print(food) // prints: ["cake"]
food += ["spaghetti"]
print(food) // prints: ["cake", "spaghetti"]
food = []
print(food) // prints: []
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: "food")
print(food) // prints: ["muesli", "banana"]
}
答案 2 :(得分:0)
let daysArray = ["Sat", "Sun", "Mon", "Tu", "Wed", "Th", "Fri"]
// Set Array Into NSUserDefaults
NSUserDefaults().setObject(daysArray, forKey: "day")
// Retrive Array from NSUserDefaults
if let daysOfWeek = NSUserDefaults().arrayForKey("day") as? [String] {
for item in daysOfWeek {
print(item)
}
}