ios - 尝试保存数组时 CoreData 出错。 'Cannot convert value of type ' String' 到预期参数类型 'NSManagedObject' '

标签 ios swift core-data

我正在使用 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)
    }

我希望应用程序保存字符串,但它不起作用。我该如何解决这个问题?

最佳答案

您混淆了文本字段的 text 属性和 Core Data 实体。显然 favorites 被声明为 [NSManagedObject] 所以你不能追加一个字符串。这就是错误消息告诉您的内容。

您必须在 insertNewCell 中插入一条新记录。最简单的解决方案是调用 save 并从 save 返回一个 bool 值以指示插入成功。

我们鼓励您使用更现代的 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 毫无意义。

关于ios - 尝试保存数组时 CoreData 出错。 'Cannot convert value of type ' String' 到预期参数类型 'NSManagedObject' ',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57887414/

相关文章:

ios - 无需字段名称即可获取文档字段的所有值

ios - 从另一个类检索字符串值

objective-c - 在后台线程上执行时,CoreData 不处理删除

iphone - core data是否会自动创建SQLite数据库文件?

ios - 推送套件未收到pushCredentials token

ios - 使用 Swift 的 UICollectionView

iphone - iOS - UIViews 不响应触摸事件

arrays - 将数据从 Firebase 读取到数组中

ios - 如何使用 Kingfisher library swift 在每个单元格中下载和缓存新图像?

ios - 我什么时候必须给 Magical Record 一个上下文?