【发布时间】:2011-02-27 16:02:12
【问题描述】:
我正在尝试获取核心数据中实体中属性的最大值。苹果有一个很好的例子here 说明如何做到这一点;但是,它对我不起作用。我的 moc 中有 10 个对象,下面的代码总是返回一个大小为 0 的数组。谁能告诉我我做错了什么?谢谢!
NSManagedObjectContext* moc = [self managedObjectContext];
// set the idx to the maximum value
NSFetchRequest* request = [[NSFetchRequest alloc] init];
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Transaction"
inManagedObjectContext:moc];
[request setEntity:entity];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression* keyPathExpression = [NSExpression expressionForKeyPath:@"idx"];
// Create an expression to represent the minimum value at the key path 'creationDate'
NSExpression* maxExpression = [NSExpression expressionForFunction:@"max:"
arguments:[NSArray arrayWithObject:keyPathExpression]];
// Create an expression description using the minExpression and returning a date.
NSExpressionDescription* expressionDescription = [[NSExpressionDescription alloc] init];
// The name is the key that will be used in the dictionary for the return value.
[expressionDescription setName:@"maxIdx"];
[expressionDescription setExpression:maxExpression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
// Execute the fetch.
NSError* error = nil;
NSArray* objects = [moc executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
int newIdx = [[[objects objectAtIndex:0] valueForKey:@"maxIdx"] intValue] + 1;
[self setPrimitiveIdx:[NSNumber numberWithInt:newIdx]];
} else {
[self setPrimitiveIdx:[NSNumber numberWithInt:1]];
}
}
【问题讨论】:
标签: objective-c cocoa core-data