簡體   English   中英

嘗試保存數組時CoreData出錯。 '無法將'String'類型的值轉換為預期的參數類型'NSManagedObject''

[英]Error in CoreData when trying to save an array. 'Cannot convert value of type 'String' to expected argument type '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)
    }

我希望應用程序保存字符串,但它不起作用。 我怎樣才能解決這個問題?

您正在混合文本字段的text屬性和核心數據實體。 顯然, favourites被聲明為[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是沒有意義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM