views:

95

answers:

1

Hi,

I have a data store of events, however I only want to show events that occur in the future.

I have a field denoting the date of the event of type NSDate.

How do I filter events that have an NSDate * date time in the past?

Thanks

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Events" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];


NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"eventDate" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];



NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];

if (mutableFetchResults == nil) {
     // Handle the error.
}
+2  A: 

You want to add a fetch predicate, an instance of NSPredicate. You're allowed to use the standard comparisons < and > in the predicate when creating it, so you can simply do:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"date > %@",
                                                           [NSDate date]];
[request setPredicate:predicate];

Then execute your request as normal. The predicate will filter out all results that don't meet the criteria date > [NSDate date], i.e. dates that are older than now. (This assumes your date field for your Core Data objects is called date; adjust accordingly if it's something else.)

For more info about predicates, you can see:

Tim