views:

1774

answers:

1

I have a Core Data model with an NSDate property. I want to filter the database by day. I assume the solution will involve an NSPredicate, but I'm not sure how to put it all together.

I know how to compare the day of two NSDates using NSDateComponents and NSCalendar, but how do I filter it with an NSPredicate?

Perhaps I need to create a category on my NSManagedObject subclass that can return a bare date with just the year, month and day. Then I could compare that in an NSPredicate. Is this your recommendation, or is there something simpler?

+11  A: 

Given a NSDate * startDate and endDate and a NSManagedObjectContext * moc:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
[request setPredicate:predicate];

NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
diciu