6

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

// 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];
}

然而,它似乎没有考虑到任何事先插入到上下文中的新对象。这是它应该如何工作的吗?它仅适用于商店中的对象吗?

我在文档中找不到任何对它的引用。

谢谢,

麦克风

4

3 回答 3

7

我收到了 Apple Developer Forums 的回复,并确认它没有考虑未保存的更改。

于 2009-10-27T21:11:44.463 回答
1

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

于 2011-02-24T08:38:56.937 回答
0

仅供参考,您可以跳过整个 NSExpression 部分并继续获取,然后使用集合运算符获取最大值。

theID = [objects valueForKeyPath:"@max.myNumbericID"];
于 2011-01-10T22:41:50.007 回答