我想要核心数据中字段的最大值,因此我设置了以下请求:
// 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];
}
然而,它似乎没有考虑任何已经插入到上下文中的新对象。这是它应该如何工作?它只适用于商店中的对象吗?
我在文档中找不到任何引用。
谢谢,
麦克
答案 0 :(得分:7)
我收到了Apple开发者论坛的回复,并确认它没有考虑未保存的更改。
答案 1 :(得分:1)
[NSFetchRequest setIncludePendingChanges:]中记录了这种行为(很差)。 NSDictionaryResultType不支持值YES。这意味着您无法在未保存的更改中使用NSExpressionDescription。
答案 2 :(得分:0)
仅供参考,您可以跳过整个NSExpression部分,然后继续获取,然后使用集合运算符获取最大值。
theID = [objects valueForKeyPath:"@max.myNumbericID"];