I have a fetchRequest that returns the max value correctly for a particular key path. The set up looks something like this:
NSExpression *keyExpression = [NSExpression expressionForKeyPath:@"distance"];
NSExpression *functionExpression = [NSExpression expressionForFunction:@"max:" arguments:@[keyExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:keyPath];
[expressionDescription setExpression:functionExpression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];
The problem is that I also need to return the value for another property on the object matching the above NSExpressionDescription. In other words, I want the value of the timestamp property returned for the managedObject from which the max: value is being returned. If I set up the fetch request like this:
NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"record"];
request.resultType = NSDictionaryResultType;
request.propertiesToFetch = @[expressionDescription, @"timestamp"];
request.propertiesToGroupBy = @[@"timestamp"];
it returns a dictionary for each of the records that has a timestamp instead of just one dictionary for the record matching the max value. Any idea how I can get the result I'm after?
Construct your fetch request to return the items you want (this could be as a dictionary or managed object). Rather than using a max expression though just set the
fetchLimit
to 1 and add a sort descriptor so that the result with the maximum value fordistance
is returned (because it is the first item in the result set).