简体   繁体   English

Swift Core Data从特定日期获取结果

[英]Swift Core Data Fetch results from a certain date

I'm fairly new to ioS dev so this might be obvious. 我对ioS dev相当新,所以这可能是显而易见的。

With Core Data, I have an Entity : 'Post' , with an attribute for "dateAdded". 使用Core Data,我有一个实体:'Post',其属性为“dateAdded”。

When the user selects an NSDate on a calendar- I want to fetch all the entries on that day only and load that into a table. 当用户在日历上选择NSDate时 - 我想仅获取当天的所有条目并将其加载到表中。

I was thinking of using a predicate where dateAdded (NSDate) would be equal to the calendarSelectedNSDate. 我在考虑使用谓词,其中dateAdded(NSDate)将等于calendarSelectedNSDate。 But I don't think that would work as their NSDates would be different because of different times. 但我认为这不会起作用,因为他们的NSD由于时间的不同会有所不同。

I would really appreciate a solution! 我真的很感激解决方案! Thank you! 谢谢!

Use NSCalendar to calculate the start and end of the selected date and create a predicate: 使用NSCalendar计算所选日期的开始和结束并创建谓词:

// get the current calendar
let calendar = NSCalendar.currentCalendar()
// get the start of the day of the selected date
let startDate = calendar.startOfDayForDate(calendarSelectedNSDate)
// get the start of the day after the selected date
let endDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: startDate, options: NSCalendarOptions())!
// create a predicate to filter between start date and end date
let predicate = NSPredicate(format: "dateAdded >= %@ AND dateAdded < %@", startDate, endDate)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM