【问题标题】:How can I get the average value of a column with Core Data?如何使用 Core Data 获取列的平均值?
【发布时间】:2010-10-18 04:54:33
【问题描述】:

如果我有以下 NSManagedObject,如何获得 number1 的平均值和 number2 的平均值?

@interface Log :  NSManagedObject  
{


}


@property (nonatomic, retain) NSNumber * number1;
@property (nonatomic, retain) NSNumber * number2;

谢谢:D

【问题讨论】:

    标签: objective-c core-data ios aggregate


    【解决方案1】:
     NSManagedObjectContext *managedObjectContext = [(AppDelegate_Shared*)[UIApplication sharedApplication].delegate managedObjectContext];
    
     NSFetchRequest *request = [[NSFetchRequest alloc] init];
     NSEntityDescription *entity = [NSEntityDescription entityForName:@"Log" inManagedObjectContext:managedObjectContext];
     [request setEntity:entity];
    
     // Specify that the request should return dictionaries.
     [request setResultType:NSDictionaryResultType];
    
     // Create an expression for the key path.
     NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"systolic"];
    
     // Create an expression to represent the minimum value at the key path 'creationDate'
     NSExpression *avgExpression = [NSExpression expressionForFunction:@"average:" 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:@"averageSystolicPressure"];
     [expressionDescription setExpression:avgExpression];
     [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;
     NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
     if (objects == nil) {
      // Handle the error.
     }
     else {
      if ([objects count] > 0) {
       NSLog(@"object count = %d", [objects count]);
    
       NSLog(@"Average systolic pressure: %d", [[[objects objectAtIndex:0] valueForKey:@"averageSystolicPressure"] integerValue] );
      }
     }
    
     [expressionDescription release];
     [request release];
    

    【讨论】:

      【解决方案2】:

      使用集合运算符@avg

      假设您已经对 Log 对象进行了提取,并将生成的 NSSet 存储在 logs 中。那么你可以简单地说:

      NSNumber *avg1 = [logs valueForKeyPath:@"@avg.number1"];
      NSNumber *avg2 = [logs valueForKeyPath:@"@avg.number2"];
      

      @avg 是少数几个可以在关键路径中与集合一起使用的运算符之一。其他一些是@max@min@sum

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-08
        • 1970-01-01
        • 2022-01-08
        • 1970-01-01
        • 2017-12-09
        • 1970-01-01
        • 2012-03-18
        • 1970-01-01
        相关资源
        最近更新 更多