I am trying to get the maximum value for an attribute in Entity in the master data. Apple has a good example here on how to do this; however, this does not work for me. I have 10 objects in my moka, and the following code always returns an array of size 0. Can someone tell me what I'm doing wrong? Thanks!
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 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]]; } }
source share