4

我已经从 NSMutableArray 的核心数据中加载了项目。每个项目在创建时都有一个截止日期,用户可以选择该截止日期。

如何排序,只显示今天到期的项目?

这是我到目前为止得到的:

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"dueDate == %@", [NSDate date]];

[allObjectsArray filterUsingPredicate: predicate]; 

但是,此代码不起作用。

感谢您的任何建议

4

3 回答 3

12

不如先在今天 00:00 计算,然后在明天 00:00 计算,然后将谓词中的日期与那些日期(>= 和 <)进行比较。因此,所有日期对象必须在这两个日期内才能被归类为“今天”。这要求您最初只计算 2 个日期,无论您的数组中有多少日期对象。

// Setup
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];

// Get todays year month and day, ignoring the time
NSDateComponents *comp = [cal components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:now];

// Components to add 1 day
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
oneDay.day = 1;

// From date  & To date
NSDate *fromDate = [cal dateFromComponents:comp]; // Today at midnight
NSDate *toDate = [cal dateByAddingComponents:oneDay toDate:fromDate options:0]; // Tomorrow at midnight

// Cleanup
[oneDay release]

// Filter Mutable Array to Today
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dueDate >= %@ && dueDate < %@", fromDate, toDate];
NSArray *filteredArray = [allObjectsArray filteredArrayUsingPredicate:predicate];

// Job Done!
于 2009-11-01T18:49:35.143 回答
1

The problem with using predicates is that if they use standard date comparison, it'll only return dates that are exactly the date and time of the given date. If you want "today" dates, you'll need to add a -isToday method somewhere (possible as an extension to NSDate), like this:

-(BOOL)dateIsToday:(NSDate *)aDate {

    NSDate *now = [NSDate date];

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *nowComponents = [cal components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit 
                                         fromDate:now];

    NSDateComponents *dateComponents = [cal components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit 
                                          fromDate:aDate];

    return (([nowComponents day] == [dateComponents day]) &&
        ([nowComponents month] == [dateComponents month]) && 
        ([nowComponents year] == [dateComponents year]));

}

Once you have that, it's simple enough to find the ones that are today:

NSMutableArray *itemsDueToday = [NSMutableArray array];

for (MyItem *item in items) {
    if ([self dateIsToday:[item date]) {
        [itemsDueToday addObject:item];
    }
}

// Done!
于 2009-10-22T09:11:48.867 回答
0

该方法-filterUsingPredicate:仅适用于可变数组(类型NSMutableArray)。

尝试使用该-filteredArrayUsingPredicate:方法,而不是:

NSString *formattedPredicateString = [NSString stringWithFormat:@"dueDate == '%@'", [NSDate date]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:formattedPredicateString];
NSArray *filteredArray = [allObjectsArray filteredArrayUsingPredicate:predicate];
于 2009-10-22T09:00:44.250 回答