【发布时间】:2020-08-20 15:58:10
【问题描述】:
我试图在用户通过 DatePicker 选择的特定日期显示保存到 Core Data 的数据。
数据以.date保存如下:
func saveBreakfast() {
let newBreakfastItem = BreakfastItem(context: self.moc)
newBreakfastItem.id = UUID()
newBreakfastItem.name = self.item.name
newBreakfastItem.calories = Int32(self.totalCalories)
newBreakfastItem.carbs = Int32(self.totalCarbs)
newBreakfastItem.protein = Int32(self.totalProtein)
newBreakfastItem.fat = Int32(self.totalFats)
newBreakfastItem.date = self.dateAdded
do {
if self.mocB.hasChanges { // saves only if changes are made
try? self.mocB.save()
}
}
}
我现在有
@State var selectedDate : Date
&
ForEach(self.BreakfastItems.filter { $0.date == selectedDate }, id: \.id) { newBreakfastItems in
但是什么都没有显示,知道这是为什么吗?这两个日期的格式不正确吗?
或者还有其他方法可以实现吗?
提前致谢!
【问题讨论】:
-
一些评论: - 您使用不同的托管对象上下文来创建实体并使用不同的上下文来保存它(moc,mocB) - 您如何获取您保存的实体?您可以在 fetch 中使用谓词而不是过滤器。 - 如果你不在其他地方使用它,变量“id”是不必要的,因为在使用 \ .self 的实体中就可以了。
-
最好不要在视图渲染时间按CoreData过滤,因为你很快就会遇到性能问题。
-
@NikosPolychronakis 我为每顿饭使用不同的上下文(mocB、mocL、mocD、mocS -> 早餐、午餐、晚餐、小吃))所以这是一个错误,但是 moc 仍然保存为 Ive以前用于一般食品。感谢您指出这一点!
-
@Asperi 注意到谢谢!
标签: swift core-data swiftui ios14