0

属性我有两个Entities如下面的图像中描绘:调用核心数据通过关系

enter image description here

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] = [] 

所以我尝试添加的属性称为theRestaurant到食品实体和这样的作品,但通过调用的关系似乎永远不会工作。

我在这里错过了一些明显的东西吗?

+0

你曾经创建'restaurantName'实体? –

回答

0

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

E.g.

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 

或者,如果你已经拥有的一些餐馆名单,不仅仅是添加新的食物对象,以其中的一个

+0

哦哇..非常感谢@livenplay - 这真的很有道理,并在您的指导下,我能够得到它的工作。我看到了这个错误 - 你必须实际申报和分配餐馆实体,这是其中的一部分,然后将其分配给关系。它现在像一种魅力 - 非常感谢! – amitsbajaj