获取实体中值的最大值

时间:2011-02-27 16:02:12

标签: objective-c cocoa core-data

我正在尝试获取核心数据中实体中属性的最大值。 Apple有一个很好的例子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]];
    }
  }

1 个答案:

答案 0 :(得分:1)

您的代码看起来对我来说,请查看以下内容

  1. 您实际上在商店中有交易对象。只需从同一个上下文中进行正常的提取。

  2. 您可以在设置上下文之前执行此操作吗?

  3. 检查是否有任何错误 - 只需记录[error localDescription]

  4. NSInteger32AttributeType是否适用于idx?

  5. idx拼写正确吗?交易?意思是,它们符合您的模型。

  6. PS:结果无关紧要,但希望你有代码样本的发布