首先,我在key-array1
中导入保存在用户默认值中的现有数组var savedArray = UserDefaults.standard.array(forKey: "array1") as! [String]
var ns = UserDefaults.standard
然后
let savedValue = name
然后
savedArray.append(savedValue!)
然后我将它保存在key-array1
中UserDefaults.standard.set(savedArray, forKey: "array1")
并同步
ns.synchronize()
但是,如果我进入另一个viewcontroller并执行此操作
let alreadyShownarray = UserDefaults.standard.object(forKey: "array1") as! [String]
print (alreadyShownarray)
然后我得到没有附加savedValue!
答案 0 :(得分:1)
尝试删除对象并添加新对象。
UserDefaults.standard.removeObject(forKey: "array1")
UserDefaults.standard.set(savedArray, forKey: "array1")
答案 1 :(得分:0)
您可以获取数组,将其分配给变量,追加元素,然后将对象设置为与获取相同的键。
func enqueue(localNotificationModel: LocalNotificationModel) {
guard let localNotificationJSON = UserDefaults.standard.value(forKey: localNotificationKey) as? [[String: Any]] else { return }
var localNotifiactions = localNotificationJSON.compactMap { LocalNotificationModel(json: $0)}
localNotifiactions.append(localNotificationModel)
UserDefaults.standard.set(localNotifiactions, forKey: localNotificationKey)
}
答案 2 :(得分:0)
您不能直接从NSUserDefault更新阵列。您必须创建一个新的数组并从NSUserDefault分配现有数组,然后可以将该新数组设置为NSUserDefault一个。
var newArray = [String]() //2.create a new array and assign the UserDefault array1 here
var ns = UserDefaults.standard
let savedArray = ns.array(forKey: "array1") as! [String] //1.this is protected cannot update directly
let savedValue: String = "name" //3. the value you wanted to append
newArray = savedArray //4. just copying the value here
newArray.append(savedValue) //5. appending the new value
ns.set(newArray, forKey: "array1") //6. now the value "name" is saved.
// array1[0] = "your initial value"
// array1[1] = "name"