4

NSMutableArray のコア データからアイテムをロードしました。各アイテムは、作成されると、ユーザーが選択する期日が与えられます。

今日が期限のアイテムだけが表示されるように並べ替えるにはどうすればよいですか?

これが私がこれまでに得たものです:

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

[allObjectsArray filterUsingPredicate: predicate]; 

ただし、このコードは機能しません。

提案をありがとう

4

3 に答える 3

12

今日の 00:00 と明日の 00:00 を計算し、述語の日付をそれら (>= と <) と比較するだけではどうですか。したがって、「今日」として分類されるには、すべての日付オブジェクトがこれら 2 つの日付内にある必要があります。これにより、配列内の日付オブジェクトの数に関係なく、最初に 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

述語を使用する際の問題は、標準の日付比較を使用すると、指定された日付と時刻が正確に一致する日付のみが返されることです。「今日」の日付が必要な場合は、次のように -isToday メソッドをどこかに追加する必要があります (NSDate の拡張として可能)。

-(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]));

}

それがあれば、今日のものを見つけるのは簡単です。

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 に答える