我想要核心数据中字段的最大值,所以我设置了以下请求:
// 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];
}
然而,它似乎没有考虑到任何事先插入到上下文中的新对象。这是它应该如何工作的吗?它仅适用于商店中的对象吗?
我在文档中找不到任何对它的引用。
谢谢,
麦克风