属性我有两个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'实体? –