【问题标题】:Getting the maximum value of a value in an Entity获取实体中值的最大值
【发布时间】: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


    【解决方案1】:

    您的代码在我看来是正确的,因此请检查以下内容

    1. 实际上,您的商店中有 Transaction 对象。只需从同一上下文中进行正常提取即可。

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

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

    4. NSInteger32AttributeType 是否适合 idx?

    5. idx 拼写正确吗?是交易吗?也就是说,它们与您的模型相匹配。

    PS:结果无关紧要,但希望你有代码示例中的版本

    【讨论】:

    • +1 打败我。我认为最可能的错误是拼写错误Transaction 或密钥路径。我会在没有表达式的情况下运行 fetch,看看你会得到什么。
    • 是的,我已经检查了几次拼写和其他内容。商店中有 10 个 Transaction 对象,idx 是一个 32 整数。我在应用程序中使用垃圾收集,因此版本无关紧要。我会检查错误日志。
    • 看来,一旦保存了持久存储,上面的方法就可以工作了;但不是在那之前。不过,我能够在替代解决方案中完全使用它。
    • 好点。是的——这种请求是针对商店完成的。
    猜你喜欢
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多