Question

I want the maximum value of a field in core data so I have set up the following request:

// Create fetch
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:context]];
[fetch setResultType:NSDictionaryResultType];

// Expression for Max ID
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"myNumbericID"];
NSExpression *minExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"maxID"];
[expressionDescription setExpression:minExpression]; 
[expressionDescription setExpressionResultType:NSDoubleAttributeType];
[fetch setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

// Execute the fetch. 
double theID = 0;
NSError *error;
NSArray *objects = [context executeFetchRequest:fetch error:&error]; 
if (objects && [objects count] > 0) { 
    theID = [((NSNumber *)[[objects objectAtIndex:0] valueForKey:@"maxID"]) doubleValue];
}

However it would appear it's not taking into account any new objects that have been inserted into the context before hand. Is this how it is supposed to work? Does it only work on objects in the store?

I can't find any reference to it in the docs.

Thanks,

Mike

Was it helpful?

Solution

I've had a response from the Apple Developer Forums and it was confirmed that it doesn't take into account unsaved changes.

OTHER TIPS

This behaviour is documented (poorly) in [NSFetchRequest setIncludePendingChanges:]. A value of YES is not supported with NSDictionaryResultType. This means that you cannot use NSExpressionDescription on unsaved changes.

FYI, you can skip the whole NSExpression section and just go ahead with the fetch, then use collection operators for the max value.

theID = [objects valueForKeyPath:"@max.myNumbericID"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top