简体   繁体   English

尝试保存数组时CoreData出错。 '无法将'String'类型的值转换为预期的参数类型'NSManagedObject''

[英]Error in CoreData when trying to save an array. 'Cannot convert value of type 'String' to expected argument type 'NSManagedObject''

I am using CoreData to save a tableView to the device. 我正在使用CoreData将tableView保存到设备。 I am relatively new to CoreData, and cannot figure this out. 我对CoreData比较陌生,无法解决这个问题。 I get the error: 我收到错误:

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

On the line: 在线上:

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)
    }

I expected the app to save the string, but it does not work. 我希望应用程序保存字符串,但它不起作用。 How can I fix this? 我怎样才能解决这个问题?

You are mixing up the text property of the text field and the Core Data entity. 您正在混合文本字段的text属性和核心数据实体。 Obviously favourites is declared as [NSManagedObject] so you can't append a string. 显然, favourites被声明为[NSManagedObject]因此您无法附加字符串。 That's what the error message is telling you. 这就是错误消息告诉你的内容。

You have to insert a new record in insertNewCell . 您必须在insertNewCell插入新记录。 The easiest solution is to call save and return a Bool from save to indicate that the insertion was successful. 最简单的解决方案是调用save并从save返回Bool以指示插入成功。

And you are encouraged to use more contemporary API. 并鼓励您使用更现代的API。 If there is no Memory subclass create one 如果没有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
    }
}

and change insertNewCell to 并将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 is pointless. beginUpdates/endUpdates是没有意义的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将“字符串”类型的值转换为预期的参数类型“ NSManagedObject” Swift - Cannot convert value of type 'String' to expected argument type 'NSManagedObject' Swift 尝试在 swift 应用程序的 Firestore 中添加数组元素时出现“无法将 'String' 类型的值转换为预期的参数类型 '[Any]'”错误 - "Cannot convert value of type 'String' to expected argument type '[Any]'" error when trying to add array element in firestore in swift app 尝试过滤数组数据时,无法将“String”类型的值转换为预期的参数类型“String.Element”(又名“Character”) - Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character') when trying to filter array data 获取时出错:“无法转换类型&#39;NSFetchRequest的值 <NSManagedObject> &#39;到预期的参数类型&#39;NSFetchRequest <NSFetchRequestResults> “” - Error in Fetch: “Cannot convert value of type 'NSFetchRequest<NSManagedObject>' to expected argument type 'NSFetchRequest<NSFetchRequestResults>'” 无法转换'String!'类型的值预期的参数类型错误 - Cannot convert value of type 'String!' to expected argument type error 尝试保存数组时出现错误-无法将类型[Data]的值转换为预期的参数类型&#39;[Dictionary <String, AnyObject> ]” - Trying to saveArray, got error - Cannot convert value of type '[Data]' to expected argument type '[Dictionary<String, AnyObject>]' 使用函数组合时的编译器错误:无法将类型`([[Character])-&gt; String`的值转换为期望的&gt;参数类型`_-&gt; _` - Compiler error when using function composition: Cannot convert value of type `([Character]) -> String` to expected > argument type `_ -> _` 无法将类型&#39;String?.Type&#39;的值转换为预期的参数类型&#39;String?&#39; - Cannot convert value of type 'String?.Type' to expected argument type 'String?' 无法将类型“ [String:Any]”的值转换为预期的参数类型“ String” - Cannot convert value of type '[String : Any]' to expected argument type 'String' 无法将类型(“字符串:字符串”)的值转换为预期的参数类型“ URL” - Cannot convert value of type ('string: String)' to expected argument type 'URL'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM