我的核心数据中有一些数据,并在表格视图中显示。当我单击单元格时,我想更新tableview行。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

            let cell = tableView.cellForRow(at: indexPath) as! ItemTableViewCell

            cell.starImage.image = UIImage(named: "Gray star icon")

            cell.selectionStyle = .none

            let context = coreData.persistentContainer.viewContext
            let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")

            do {
                let result = try context.fetch(request)
                let img = UIImage(named: "Gray star icon")
                for data in result as! [NSManagedObject] {

                    let data = img!.pngData() as NSData?

                    data?.setValue(data, forKey: "starImage")
                 }

            } catch {
                print("Failed")
            }

            coreData.saveContext()
            tableView.reloadData()
        }



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? ItemTableViewCell else {
        return UITableViewCell()
    }

    cell.itemName.text = itemCategoryNameArray[indexPath.row]
    cell.itemDescription.text = itemDescriptionArray[indexPath.row]
    cell.itemCategory.text = itemCategoryTypeArray[indexPath.row]
    cell.starImage.image = UIImage(data: itemStarArray[indexPath.row])
    cell.profileImage.image = UIImage(data: itemImageArray[indexPath.row])
    return cell
}


但是我遇到了一些错误:-


  由于未捕获的异常“ NSUnknownKeyException”而终止应用程序,
  原因:'[
  setValue:forUndefinedKey:]:此类不是键值
  符合关键starImage的编码要求。”

最佳答案

请合并您的变量名称:循环中有两个不同的data变量,这会导致混淆和错误

更好

for item in result as! [NSManagedObject] {
   let data = img!.pngData() as? NSData
   item.setValue(data, forKey: "starImage")
}


不过,我建议使用更具体的类型,并且仅创建一次图像

let request = NSFetchRequest<Item>(entityName: "Item")

do {
    let result = try context.fetch(request)
    let img = UIImage(named: "Gray star icon")
    let data = img!.pngData() as? NSData
    for item in result {
       item.starImage = data
    }
} catch {
    print("Failed", error)
}

关于swift - 更新tableview和coredata,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55449066/

10-13 09:26