Core data NSDictionaryResultType表达式不考虑新插入的对象

Core data NSDictionaryResultType表达式不考虑新插入的对象,core-data,nsfetchrequest,Core Data,Nsfetchrequest,我想要核心数据中字段的最大值,因此我设置了以下请求: // Create fetch NSFetchRequest *fetch = [[NSFetchRequest alloc] init]; [fetch setEntity:[NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:context]]; [fetch setResultType:NSDictionaryResultType]; // Expr

我想要核心数据中字段的最大值,因此我设置了以下请求:

// 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];
}
然而,它似乎并没有考虑到之前插入到上下文中的任何新对象。这就是它的工作原理吗?它是否仅适用于商店中的对象

我在文件里找不到它的任何参考资料

谢谢


Mike

我从Apple开发者论坛收到了回复,确认它没有考虑未保存的更改。

仅供参考,您可以跳过整个NSExpression部分,继续进行获取,然后使用收集操作符获取最大值

theID = [objects valueForKeyPath:"@max.myNumbericID"];

此行为在[NSFetchRequest setIncludePendingChanges:]中记录(很差)。NSDictionaryResultType不支持值YES。这意味着您不能在未保存的更改上使用NSExpressionDescription。

虽然这会起作用,但它将依赖于首先将符合条件的每个对象放入内存。在我的情况下,这将是太多的对象。我需要核心数据通过一个针对数据存储的聚合SQL语句来计算它。在这种情况下,您可以只使用NSSortDescriptor和FETCHTLIMIT 1,然后只加载单个对象。