【发布时间】:2017-05-04 06:17:14
【问题描述】:
我有两个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] = []
所以我尝试在 Food Entity 中添加一个名为 theRestaurant 的属性,这很有效,但通过关系调用似乎永远不会奏效。
我在这里遗漏了什么明显的东西吗?
【问题讨论】:
-
您是否创建过
restaurantName实体?
标签: swift uitableview core-data attributes nsfetchedresultscontroller