NSDictionaryResultType expression not taking into account newly inserted objects

时光毁灭记忆、已成空白 提交于 2019-12-18 06:43:39

问题


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


回答1:


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




回答2:


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.




回答3:


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"];


来源:https://stackoverflow.com/questions/1632029/nsdictionaryresulttype-expression-not-taking-into-account-newly-inserted-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!