gpt4 book ai didi

ios - anyObject 的 NSUserDefaults arrayForKey 值没有成员 removeAtIndex (Swift)

转载 作者:行者123 更新时间:2023-11-28 16:14:53 24 4
gpt4 key购买 nike

我正在使用 NSUserDefaults 来存储一个数组(字符串),并且在加载它时,它似乎被解释为一个 AnyObject 而不是一个数组。我不明白这是怎么可能的,因为我默认使用 arrayForKey 方法,我认为它应该返回一个数组?

我得到的确切错误是:

Value of type '[AnyObject]?' has no member 'removeAtIndex'

发生在 shoppingListDefaults.arrayForKey("ShoppingList").removeAtIndex(indexPath.row)

let shoppingListDefaults = NSUserDefaults.standardUserDefaults()
let deleteAction = UITableViewRowAction(style: .Normal, title: "Delete") { (rowAction:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
shoppingListDefaults.arrayForKey("ShoppingList").removeAtIndex(indexPath.row)
self.slItems.reloadData() // `slItems` is the IBOutlet for a UITableView
}
deleteAction.backgroundColor = UIColor.redColor()
return [deleteAction]

最佳答案

arrayForKey 返回一个可选的,所以你必须先打开它,然后才能调用它上面的任何其他东西。您也不能直接编辑从默认值获得的数组,因为它是不可变的。您必须编辑数组,然后使用更新数组更新默认值。

尝试:

if var list = shoppingListDefaults.arrayForKey("ShoppingList") {
list.removeAtIndex(indexPath.row)
shoppingListDefaults.setArray(list, forKey: "ShoppingList")
}

关于ios - anyObject 的 NSUserDefaults arrayForKey 值没有成员 removeAtIndex (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39211565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com