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
This code from Core Data Programming Guide should work.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];
[request setEntity:entity];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"creationDate"];
// Create an expression to represent the maximum value at the key path 'creationDate'
NSExpression *maxExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyPathExpression]];
// Create an expression description using the maxExpression and returning a date.
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
// The name is the key that will be used in the dictionary for the return value.
[expressionDescription setName:@"maxDate"];
[expressionDescription setExpression:maxExpression];
[expressionDescription setExpressionResultType:NSDateAttributeType];
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
// Execute the fetch.
NSError *error = nil;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
NSLog(@"Maximum date: %@", [[objects objectAtIndex:0] valueForKey:@"maxDate"]);
}
}
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];
}
The issue was that this line is wrong:
[fetch setResultType:NSDictionaryResultType];
The result type should have been NSManagedObjectResultType
Regards
Darren.