Swift CoreData从关系中保存和获取

时间:2017-01-20 09:47:10

标签: swift core-data

我的swift应用程序中有coredata。我能够将两个textfields.text保存到核心数据并获取它,但这两个属性是1个实体的一部分。我还有一些其他实体已建立关系。

当我保存到核心数据时,会发生两个字符串,但关系字符串为nil,应用程序崩溃。

以下是我的一些设置

Screenshot of core data

// MARK:NSFetchedResultsControllerDelegate

extension SavedPalauttesViewController: NSFetchedResultsControllerDelegate {

  func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {


    tableView.beginUpdates()
  }

  func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {


    tableView.endUpdates()
  }



  func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {


    switch(type) {

    case .insert:
      if let indexPath = newIndexPath {
        tableView.insertRows(at: [indexPath], with: .fade)
      }
      break

    case .delete:
      if let indexPath = indexPath {
        tableView.deleteRows(at: [indexPath], with: .fade)
      }
      break

    case.update:
      if let indexPath = indexPath{
        let cell = tableView.cellForRow(at: indexPath) as! LocalPalautteTableViewCell
        configureCell(cell: cell, indexPath: indexPath as NSIndexPath)
      }
      break

    case .move:
      if let indexPath = indexPath {
        tableView.deleteRows(at: [indexPath], with: .fade)
      }
      if let indexPath = newIndexPath {
        tableView.insertRows(at: [indexPath], with: .fade)
      }
      break

    }
  }

  func attemptFetch() {

    let fetchRequest: NSFetchRequest<Palautte> = Palautte.fetchRequest()

    let nameSort = NSSortDescriptor(key: "name", ascending: false)
    fetchRequest.sortDescriptors = [nameSort]

    let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

    controller.delegate = self

    self.controller = controller

    do {

      try controller.performFetch()

    } catch {

      let error = error as NSError
      print("\(error)")

    }




  }

}

现在类型字符串的类别和字符串类型的名称正常工作

但是当我尝试保存任何背景颜色或前景时...我得到了nil并且崩溃了

这是我尝试保存到核心数据的一部分

palauttePalautte.category = finalPalautteCategoryValue ?? ""


palauttePalautte.toBackgroundColor?.redValue = String(Int(redBackgroundColorValue))

但在第二个vc上,当我试图获取它的值时,我崩溃了

let backRed = palautte.toBackgroundColor?.redValue ?? ""

我做错了什么?

0 个答案:

没有答案
相关问题