views:

353

answers:

2

I have an Entity 'Event' which contains a NSDate 'AccidentDate'. I am trying to do a fetch request to grab only the most recent 'AccidentDate' but I am not sure how to set up the predicate to grab only the last 'AccidentDate'

Below is my code so far...

NSFetchRequest *fetchRequest1 = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];

[fetchRequest1 setEntity:entity];

NSPredicate *predicate; //unknown code here [fetchRequest1 setPredicate:predicate];

NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest1 error:&error];

[fetchRequest1 release];

Any help would be greatly appreciated. Thanks

A: 

I would fetch all Events sorted by AccidentDate with no predicate and grab the first one from the array.

gerry3
+1  A: 

You can apply an array of sort descriptors directly to the NSFetchRequest and you can further set its fetch limit to 1. That creates the following code:

NSFetchRequest *fetchRequest1 = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event"  inManagedObjectContext:[self managedObjectContext]];

[fetchRequest1 setEntity:entity];

NSSortDescriptor *dateSort = [[NSSortDescriptor alloc] initWithKey:@"accidentDate" ascending:NO];
[fetchRequest1 setSortDescriptors:[NSArray arrayWithObject:dateSort]];
[dateSort release], dateSort = nil;

[fetchRequest1 setFetchLimit:1];

NSManagedObject *latest = [[[self managedObjectContext] executeFetchRequest:fetchRequest1 error:&error] lastObject];

[fetchRequest1 release], fetchRequest1 = nil;
Marcus S. Zarra