Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionaryResultType expression not taking into account newly inserted objects

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

like image 741
Michael Waterfall Avatar asked Oct 27 '09 16:10

Michael Waterfall


2 Answers

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

like image 59
Michael Waterfall Avatar answered Oct 30 '22 06:10

Michael Waterfall


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.

like image 33
Aderstedt Avatar answered Oct 30 '22 06:10

Aderstedt