屬性我有兩個Entities
如下面的圖像中描繪:調用核心數據通過關係
Food
和Restaurant
。
我知道命名有點關閉,但基本上,我建立了一個食品項目列表。用戶將添加具有食物名稱和餐廳名稱的新條目。我處於開發的最初階段。
所以在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
到食品實體和這樣的作品,但通過調用的關係似乎永遠不會工作。
我在這裏錯過了一些明顯的東西嗎?
你曾經創建'restaurantName'實體? –