8

NSFetchedResultsControllerUITableViewControllerを使用してCoreDataデータベースからデータを読み込みます。NSPredicateとCoreData - iOSでDate属性が "today"(または昨夜午前12時から今夜午前12時まで)かどうかを判断します。

私はNSDateオブジェクトを "startTime"とラベル付けされたこの日付属性に保存しました。そして、私はこのようになりますNSPredicateを使用することにより、今日のデータを取得しようとしている:私はゼロの結果を得ている

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"startDate == %@", 
          todaysDate]; 

NSDateオブジェクトはちょうど1970年1月1日から数秒間または何秒間何秒間保持しているので、これを理解していますか?したがって、1111111111111と1111111111112を比較すると、同じ日に2つの別個のNSDateオブジェクトが等しいことになります。

したがって、NSPredicateはどのようにしてフォーマットできますか?私はその2つのNSDateのオブジェクトを作成すると推測します:1つは昨夜の午前12時に、もう1つは今夜午前12時に開始し、startDateを比較して、その2つの間にあるかどうかを確認しますNSDate

私はNSPredicateに新しくなっています。これはどのように達成できますか?

+0

解決策を質問の中に入れるのではなく、答えに入れる必要があります。 – yuji

+0

まだ十分な担当者がいないので、@yujiはできません。 –

+0

あなたの答えを**あなたの**解決策に入れることができるかもしれません。その間、私はあなたが既に祐司の答えを受け入れているのを見てそれを編集しました。リビジョン履歴を表示することで、ソリューションを復旧できます。ありがとう。 – Kev

答えて

24

NSCompoundPredicateを使用してください。

firstDateが今朝午前12時で、 secondDateは午前12時今夜ある
NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:@"startDate > %@", firstDate]; 
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"startDate < %@", secondDate]; 

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:firstPredicate, secondPredicate, nil]]; 

P.S. 、午前12時今夜を取得するには

NSCalendar *calendar = [NSCalendar calendar]; // gets default calendar 
NSCalendarComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, and day for today's date 
NSDate *firstDate = [calendar dateFromComponents:components]; // makes a new NSDate keeping only the year, month, and day 

変更components.day:ここでは、今朝午前12時を取得する方法です。

+1

大変ありがとうございます。 - andPredicateWithSubpredicates(小文字のP)、NSCalendarComponentsの代わりにNSDateComponentsを使用します。 – amergin

関連する問題