I need to find out the maximum value of an attribute of a core data entity.
I\'m still firmly in the Cocoa learning curve, and this is a simple test app that I\'m us
I had to solve a similar problem and approached it slightly differently by:
The code for this is below. I am querying an entity called 'entityName' and retrieving the max value for the attribute 'sequenceId'.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *res = [NSEntityDescription entityForName:@"entityName" inManagedObjectContext:managedObjectContext];
[request setEntity:res];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sequenceId" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
[request setFetchLimit:1];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
[request release];
if (results == nil) {
NSLog(@"error fetching the results: %@",error);
}
NSInteger maximumValue = 0;
if (results.count == 1) {
Result *result = (Result*)[results objectAtIndex:0];
maximumValue = [result.sequenceId integerValue];
}