今天由NSDate排序NSArray

Cof*_*ffe 4 iphone cocoa cocoa-touch core-data nsdate

我已经从NSMutableArray中的核心数据加载了项目.创建每个项目时,将给出用户选择的截止日期.

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

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

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

[allObjectsArray filterUsingPredicate: predicate]; 
Run Code Online (Sandbox Code Playgroud)

但是,此代码不起作用.

谢谢你的任何建议

Mic*_*all 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!
Run Code Online (Sandbox Code Playgroud)

  • +1这可能是你最好的选择.`> = && <`的替代方法是使用`BETWEEN`关键字:`NSPredicate*predicate = [NSPredicate predicateWithFormat:@"dueDate BETWEEN%@",[NSArray arrayWithObjects:fromDate,toDate,nil]];`(注意你在使用`predicateWithFormat:`时不必构造`predicateString`对象 (5认同)