当向左滑动并单击“收藏”按钮时,我按照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)

最佳答案

不要在cellForRowAt之外对单元格进行出列。别那样做。手机没用。
使用专用的APIarray(forKeyUserDefaults读取数组,并将类型转换为预期的类型,而不是未指定的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]
}

10-08 06:29