Search code examples
iphone-sdk-3.0core-datanspredicate

CoreData Fetch Request with Most recent Predicate


I have an Entity "Event" which contains a NSDate attribute named "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


Solution

  • 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;