NSPredicate 与 NSDate 按天/月过滤但不是年 [英] NSPredicate with NSDate filtering by day/month but not year

查看:75
本文介绍了NSPredicate 与 NSDate 按天/月过滤但不是年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个谓词,该谓词需要使用属性 creationDate 过滤对象列表,该属性是一个 NSDate 对象.我想获取具有相同日期和月份但不是同一年的对象列表.实际上,我想要过去今天(如日/月)发生的对象.我怎样才能创建这个谓词?例如:今天是 2016 年 7 月 27 日,我想要所有将 7 月 27 日作为creationDate 的对象.

I need to create a predicate which needs to filter a list of objects using the property creationDate which is a NSDate object. I want to obtain the list of objects that have the same day and month, but not the same year. Practically, I want the objects that occurred today (as day/month) in the past. How can I create this predicate? For example : today is July 27th 2016 and I want all the objects that have July 27th as creationDate.

推荐答案

首先,从日期中提取日期和月份...

First, to extract a day and month from a date...

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
NSInteger day = [components day];
NSInteger month = [components month];

接下来,(一种方式)构建谓词...

Next, (one way) to build a predicate...

[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary * bindings) {
    // object must be cast to the type of object in the list
    MyObject *myObject = (MyObject *)object;
    NSDate *creationDate = myObject.creationDate;

    // do whatever you want here, but this block must return a BOOL
}];

把这些想法放在一起......

Putting those ideas together...

- (NSPredicate *)predicateMatchingYearAndMonthInDate:(NSDate *)date {
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
    NSInteger day = [components day];
    NSInteger month = [components month];

    return [NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary * bindings) {
        MyObject *myObject = (MyObject *)object;
        NSDate *creationDate = myObject.creationDate;
        NSDateComponents *creationComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:creationDate];
        NSInteger creationDay = [creationComponents day];
        NSInteger creationMonth = [creationComponents month];
        return day == creationDay && month == creationMonth;
    }];
}

就是这样.使用一些 NSDate 构建您想要在数组中匹配的日期和月份的谓词,然后在数组上运行该谓词 (filteredArrayUsingPredicate:).

That's it. Build the predicate with some NSDate who's day and month you want to match in the array, then run that predicate on the array (filteredArrayUsingPredicate:).

NSDate *today = [NSDate date];
NSPredicate *predicate = [self predicateMatchingYearAndMonthInDate:today];
NSArray *objectsCreatedToday = [myArray filteredArrayUsingPredicate:predicate];

这篇关于NSPredicate 与 NSDate 按天/月过滤但不是年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆