如何将 FetchedResultsController 限制为给定日期的对象
How to restrict FetchedResultsController to objects in a given day
我正在尝试创建一个 UITableView
来填充选定日期(特别是 yesterday
、today
和 tomorrow
)的对象。在我的 CoreData 模型中,所讨论的实体是 属性 date with type
Date`.
为了获得 yesterday
、today
和 tomorrow
,我这样做(按照 this WWDC session 的规定):
var today = Date()
var yesterday = calendar.date(byAdding: .day, value: -1, to: self.date)
var tomorrow = calendar.date(byAdding: .day, value: 1, to: self.date)
并执行:
today = calendar.startOfDay(for: today)
yesterday = calendar.startOfDay(for: yesterday)
tomorrow = calendar.startOfDay(for: tomorrow)
获得所有日期后,我不知道该怎么做。目前我的获取结果控制器看起来像:
lazy var fetchedResultsController: NSFetchedResultsController<Entry> = {
let fetchRequest: NSFetchRequest<Entry> = Entry.fetchRequest()
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
// Create Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: app_delegate.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
// Configure Fetched Results Controller
fetchedResultsController.delegate = self
return fetchedResultsController
}()
如何将 fetchedResultsController
限制为这些日期之一,如果可能的话,我会使用 Calendar
s 方法来做到这一点:isDateInToday()
?
向提取请求添加谓词。
request.predicate = NSPredicate(format: "date > %@ && date < %@",
today as NSDate, tomorrow as NSDate)
我正在尝试创建一个 UITableView
来填充选定日期(特别是 yesterday
、today
和 tomorrow
)的对象。在我的 CoreData 模型中,所讨论的实体是 属性 date with type
Date`.
为了获得 yesterday
、today
和 tomorrow
,我这样做(按照 this WWDC session 的规定):
var today = Date()
var yesterday = calendar.date(byAdding: .day, value: -1, to: self.date)
var tomorrow = calendar.date(byAdding: .day, value: 1, to: self.date)
并执行:
today = calendar.startOfDay(for: today)
yesterday = calendar.startOfDay(for: yesterday)
tomorrow = calendar.startOfDay(for: tomorrow)
获得所有日期后,我不知道该怎么做。目前我的获取结果控制器看起来像:
lazy var fetchedResultsController: NSFetchedResultsController<Entry> = {
let fetchRequest: NSFetchRequest<Entry> = Entry.fetchRequest()
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
// Create Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: app_delegate.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
// Configure Fetched Results Controller
fetchedResultsController.delegate = self
return fetchedResultsController
}()
如何将 fetchedResultsController
限制为这些日期之一,如果可能的话,我会使用 Calendar
s 方法来做到这一点:isDateInToday()
?
向提取请求添加谓词。
request.predicate = NSPredicate(format: "date > %@ && date < %@",
today as NSDate, tomorrow as NSDate)