您不能简单地使用您的日期与今天的日期进行比较:
let today = Date() let datePredicate = NSPredicate(format: "%K == %@",#keyPath(ModelType.date),today)
它不会显示任何内容,因为您的日期不太可能是完全比较日期(它还包括秒和毫秒)
解决方案是这样的:
// Get the current calendar with local time zone var calendar = Calendar.current calendar.timeZone = NSTimeZone.local // Get today's beginning & end let dateFrom = calendar.startOfDay(for: Date()) // eg. 2016-10-10 00:00:00 let dateTo = calendar.date(byAdding: .day,value: 1,to: dateFrom) // Note: Times are printed in UTC. Depending on where you live it won't print 00:00:00 but it will work with UTC times which can be converted to local time // Set predicate as date being today's date let fromPredicate = NSPredicate(format: "%@ >= %@",date as NSDate,dateFrom as NSDate) let toPredicate = NSPredicate(format: "%@ < %@",dateTo as NSDate) let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate,toPredicate]) fetchRequest.predicate = datePredicate
这是迄今为止最简单的&只显示具有今天日期的对象的最短方式.