核心数据谓词按今天的日期过滤

时间:2016-10-28 19:36:01

标签: swift core-data swift3 nspredicate

我遇到了这方面的问题,我没有在SO上找到合适的答案所以我会在这里留下一个小教程。

目标是在今天的日期过滤提取的对象。

注意:它与Swift 3兼容。

3 个答案:

答案 0 :(得分:19)

您不能简单地将日期与今天的日期进行比较:

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: "%@ < %@", date as NSDate, dateTo as NSDate)
let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate, toPredicate])
fetchRequest.predicate = datePredicate

这是迄今为止最简单的&amp;仅显示具有今天日期的对象的最短方式。

答案 1 :(得分:3)

在swift4中,Lawrence413可以简化一下:

- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    CGImageRef cgImage;
    CreateCGImageFromCVPixelBuffer(pixelBuffer, &cgImage);
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.source_material.diffuse.contents = image;
        [cube[0] replaceMaterialAtIndex:0 withMaterial:self.source_material];
        self.mirror_material.diffuse.contents = self.source_material.diffuse.contents;
        [cube[1] replaceMaterialAtIndex:0 withMaterial:self.mirror_material];
        });
        CGImageRelease(cgImage);
}

它摆脱了//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) 部分,使代码具有更好的可读性。

答案 2 :(得分:1)

添加到Lawrence413的答案中可能会有所帮助,即使用具有今天日期的属性来过滤记录列表,可以使用:

 let fromPredicate = NSPredicate(format: "datetime >= %@", dateFrom as NSDate)
let toPredicate = NSPredicate(format: "datetime < %@",  dateToUnwrapped as NSDate)

...其中“ datetime是属性的名称”