如何解决如何按日期过滤核心数据项?
我试图显示用户通过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
但是什么也没显示,为什么知道呢?两个日期格式不正确吗?
还是有另一种方法可以实现?
谢谢!
解决方法
您可以使用以下功能在特定日期从核心数据加载早餐项目:
func loadBreakfastItemsFromCoreData(at date: Date) -> [BreakfastItems] {
let request: NSFetchRequest<BreakfastItems> = BreakfastItems.fetchRequest()
let startDate = Calendar.current.startOfDay(date)
var components = DateComponents()
components.day = 1
components.second = -1
let endDate = Calendar.current.date(byAdding: components,to: startDate)!
request.predicate = NSPredicate(format: "date >= %@ AND date <= %@",startDate,endDate)
// Optional: You can sort by date
request.sortDescriptors = [NSSortDescriptor(key: "date",ascending: true)]
do {
return try mocB.fetch(request)
} catch {
print("Error fetching data from context: \(error)")
}
return []
}
如果您使用不同的上下文,请确保您知道该怎么做。如果您不知道,请阅读或仅使用一种上下文。在我的示例中,我使用了您的背景上下文,但是请随时切换到主要上下文。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。