首页 > 解决方案 > 尝试保存数组时 CoreData 出错。'无法将'String'类型的值转换为预期的参数类型'NSManagedObject''

问题描述

我正在使用 CoreData 将 tableView 保存到设备。我对 CoreData 比较陌生,无法弄清楚这一点。我得到错误:

'Cannot convert value of type 'String' to expected argument type 'NSManagedObject''

在线上:

favourites.append(addNewMemory.text!)
//MARK:- Core Data
    func save(name: String) {

      guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
        return
      }

      // 1
      let managedContext =
        appDelegate.persistentContainer.viewContext

      // 2
      let entity =
        NSEntityDescription.entity(forEntityName: "Memory",
                                   in: managedContext)!

      let person = NSManagedObject(entity: entity,
                                   insertInto: managedContext)

      // 3
      person.setValue(name, forKeyPath: "name")

      // 4
      do {
        try managedContext.save()
        favourites.append(person)
      } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
      }
    }

    var favourites: [NSManagedObject] = []


   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return favourites.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "Cell")
        /*cell.imageView?.image = UIImage(named: "applelogo")
        cell.imageView?.setRounded()
        cell.imageView?.clipsToBounds = true
        */

        let favMemory = favourites[indexPath.row]
        cell.textLabel?.text = favMemory.value(forKeyPath: "name") as? String

        return cell
    }
@IBAction func addButtonTapped(_ sender: UIButton) {
        insertNewCell()
    }

    func insertNewCell() {

        favourites.append(addNewMemory.text!)

        let indexPath = IndexPath(row: favourites.count - 1, section: 0)
        tableView.beginUpdates()
        tableView.insertRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()

        addNewMemory.text = ""
        view.endEditing(true)
    }

我希望应用程序保存字符串,但它不起作用。我怎样才能解决这个问题?

标签: iosswiftcore-data

解决方案


您正在混淆text文本字段和核心数据实体的属性。显然favourites被声明为[NSManagedObject]所以你不能附加一个字符串。这就是错误消息告诉您的内容。

您必须在insertNewCell. 最简单的解决方案是调用save并返回一个 Bool fromsave以指示插入成功。

我们鼓励您使用更现代的 API。如果没有Memory子类创建一个

var favourites = [Memory]()

...

func save(name: String) -> Bool {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate // force unwrapping is perfectly fine

    // 1
    let managedContext = appDelegate.persistentContainer.viewContext

    // 2
    let person = Memory(context: managedContext)

    // 3
    person.name = name

    // 4
    do {
      try managedContext.save()
      favourites.append(person)
      return true
    } catch let error as NSError {
      print("Could not save. \(error), \(error.userInfo)")
      return false
    }
}

并更改insertNewCell

func insertNewCell() {
    guard save(name: addNewMemory.text!) else { return }
    let indexPath = IndexPath(row: favourites.count - 1, section: 0)
    tableView.insertRows(at: [indexPath], with: .automatic)
    addNewMemory.text = ""
    view.endEditing(true)
}

beginUpdates/endUpdates是没有意义的。


推荐阅读