I'm trying to get the maximum value for an attribute in an Entity in core data. Apple has a nice example here of how to do this; however, it doesn't work for me. I have 10 objects in my moc and the following code always returns an array of size 0. Can anyone tell me what I am doing wrong? Thanks!
NSManagedO开发者_如何学GobjectContext* 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]];
}
}
Your code looks right to me, so check the following
You actually have Transaction objects in your store. Just do a normal fetch from the same context.
Could you be doing this before you set up the context?
Check to see if there's anything in error -- just log
[error localDescription]
Is NSInteger32AttributeType right for idx?
Is idx spelled correctly? Is Transaction? Meaning, they match your model.
PS: It won't matter for the result, but hopefully you have the releases from the code sample
精彩评论