Cayden
Cayden

Reputation: 277

Getting the maximum value of a value in an Entity

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!

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

Upvotes: 2

Views: 663

Answers (1)

Lou Franco
Lou Franco

Reputation: 89142

Your code looks right to me, so check the following

  1. You actually have Transaction objects in your store. Just do a normal fetch from the same context.

  2. Could you be doing this before you set up the context?

  3. Check to see if there's anything in error -- just log [error localDescription]

  4. Is NSInteger32AttributeType right for idx?

  5. 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

Upvotes: 1

Related Questions