【问题标题】:Calling a Core Data attribute through a relationship通过关系调用 Core Data 属性
【发布时间】:2017-05-04 06:17:14
【问题描述】:

我有两个Entities,如下图所示:

FoodRestaurant

我知道现在命名有点不对劲,但基本上,我正在建立一个食品清单。用户将添加带有食物名称和餐厅名称的新条目。我正处于发展的早期阶段。

所以在AddViewController 和保存方法中,我有:

if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
            foodEntry = FoodManagedObject(context: appDelegate.persistentContainer.viewContext)
            foodEntry.nameOfFood = foodNameTextField.text
            foodEntry.restaurantName?.nameOfRestaurant = restaurantNameTextField.text

声明变量:

var foodEntry:FoodManagedObject!

TimelineView 中,使用NSFetchedResultsController,我正在获取FoodManagedObject 并能够在标签中显示食物的名称。但是,餐厅的名称不显示。

所以,我正在适当地获取:

let fetchRequest: NSFetchRequest<FoodManagedObject> = FoodManagedObject.fetchRequest()
        let sortDescriptor = NSSortDescriptor(key: "nameOfFood", ascending: true)
        fetchRequest.sortDescriptors = [sortDescriptor]

        if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
            let context = appDelegate.persistentContainer.viewContext
            fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
            fetchedResultsController.delegate = self

            do {
                try fetchedResultsController.performFetch()
                if let fetchedObjects = fetchedResultsController.fetchedObjects {
                    foods = fetchedObjects
                }
            } catch {
                print(error)
            }
        }

cellForRow:

cell.foodNameLabel.text = foods[indexPath.row].nameOfFood

cell.restaurantLabel.text = foods[indexPath.row].restaurantName?.nameOfRestaurant

我没有收到任何错误,但餐厅的名称从不显示。

食物是:

var foods:[FoodManagedObject] = []

所以我尝试在 Food Entity 中添加一个名为 theRestaurant 的属性,这很有效,但通过关系调用似乎永远不会奏效。

我在这里遗漏了什么明显的东西吗?

【问题讨论】:

  • 您是否创建过restaurantName 实体?

标签: swift uitableview core-data attributes nsfetchedresultscontroller


【解决方案1】:

您正在创建对象之间的关系,而不是它们的值 这意味着,当您保存新的食物对象时,您必须分配已经存在的餐厅实体对象或创建新的实体对象。 您不能只分配对象值而不初始化餐厅对象。

例如

foodEntry = FoodManagedObject(context: appDelegate.persistentContainer.viewContext)
foodEntry.nameOfFood = foodNameTextField.text

// Here you must to load existing Restaurant entity object from database or create the new one        
let restaurant = RestaurantManagedObject(context: appDelegate.persistentContainer.viewContext)
restaurant.nameOfRestaurant = restaurantNameTextField.text

foodEntry.restaurantName = restaurant // Object instead of value

或者,如果您已经有一些餐馆列表,则不仅仅是将新的食物对象添加到其中一个

【讨论】:

  • 哦哇.. 非常感谢@livenplay - 这真的很有意义,在你的指导下,我能够让它工作。我看到了错误 - 您必须实际声明和分配餐厅实体,这是其中的一部分,然后将其分配给关系。它现在就像一个魅力 - 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2010-12-19
  • 2013-10-13
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
  • 2010-10-25
  • 2010-10-25
  • 1970-01-01
相关资源
最近更新 更多