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