Reputation: 21003
I am trying to optimize a fetch request for Core Data.
I have an entity with an attribute called lastModifiedDate that is an NSDate object. I need to query my database for the most recent lastModifiedDate property. I have the following code which works fine in small datasets, but with a database that has 40k records this query runs like crap.
NSDate *mostRecentLastModifiedDate = nil;
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
[request setFetchLimit:1];
[request setPropertiesToFetch:[NSArray arrayWithObject:@"lastModifiedDate"]];
NSSortDescriptor *dateSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastModifiedDate" ascending:NO];
[request setSortDescriptors:[NSArray arrayWithObject:dateSortDescriptor]];
[dateSortDescriptor release];
NSError *error = nil;
NSArray *result = [self.managedObjectContext executeFetchRequest:request error:&error];
if (error) {
NSLog(@"Error fetching most recent lastModifiedDate property for %@ entity, error details: %@", entityName, error);
} else if ([result count] > 0) {
mostRecentLastModifiedDate = [[[[result objectAtIndex:0] valueForKey:@"lastModifiedDate"] copy] autorelease];
} else {
mostRecentLastModifiedDate = [NSDate distantPast];
}
[request release];
return mostRecentLastModifiedDate;
Upvotes: 1
Views: 383
Reputation: 21003
Marking the lastModifiedDate attribute as indexed in the Data Model made this query extremely fast, would still be interested if there is a better approach to do this though.
Upvotes: 1