0

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?

Mark Armstrong
  • 819
  • 6
  • 9

1 Answers1

1

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 for distance is returned (because it is the first item in the result set).

Wain
  • 118,658
  • 15
  • 128
  • 151
  • Thanks Wain. That's not a bad way to go but I was hoping to use the NSExpressionDescription. The only way I've been able to make it work so far with the NSExpressionDescription is to have it return the objectID along with the max value and then call existingObjectWithID: to return the value I'm after. Not sure there is any other way to go about it but I would love to be wrong on this one! – Mark Armstrong Aug 09 '13 at 06:21
  • Why do you want to keep the expression? – Wain Aug 09 '13 at 06:41
  • I have a generic method that usually just returns the max value but would like the option to also return the associated timestamp for the object the max value came from. – Mark Armstrong Aug 09 '13 at 16:31
  • It will still get the max value without using the expression. – Wain Aug 09 '13 at 16:55