我遵循This的答案,以向左滑动并单击“收藏夹”按钮将数据保存到数组中。到目前为止,我已经完成了
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { (action, indexPath) in
var favorites : [String] = []
let defaults = UserDefaults.standard
if let favoritesDefaults : AnyObject? = defaults.object(forKey: "favorites") as AnyObject {
favorites = favoritesDefaults! as! [String]
}
let cell = self.myTableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! TableViewCell
favorites.append(itemList[indexPath.row])
defaults.set(favorites, forKey: "favorites")
defaults.synchronize()
}
return [favorite]
}
数组列表
var itemList = [ "item1", "item2", "item3", "item4", "item5",
"item6", "item7", "item8", "item" , "item", "Gobbling"]
当我单击“收藏夹”按钮时,它会显示错误
无法将类型'NSNull'(0x22e386f28)的值强制转换为'NSArray'(0x22e386960)
答案 0 :(得分:3)
请勿使cellForRowAt
之外的单元出队。绝对不要那样做。该单元仍未使用。
使用专用API array(forKey
从UserDefaults
读取数组并将类型强制转换为期望的类型,而不是未指定的Any(Object)
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let favorite = UITableViewRowAction(style: .normal, title: "Favorite") { [unowned self] (action, indexPath) in
let defaults = UserDefaults.standard
var favorites = defaults.array(forKey: "favorites") as? [String] ?? []
favorites.append(self.itemList[indexPath.row])
defaults.set(favorites, forKey: "favorites")
}
return [favorite]
}