How can I get the average value of a column with C

2019-07-17 03:04发布

If I have the following NSManagedObject, how can I get the average of values for number1 and the average of values for number2?

@interface Log :  NSManagedObject  
{


}


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

Thanks :D

2条回答
三岁会撩人
2楼-- · 2019-07-17 03:24

Use the collection operator @avg.

Let's say you've already done a fetch for your Log objects and stored the resulting NSSet in logs. Then you can simply say:

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

@avg is one of a small handful of operators that you can use with collections in key paths. A few others are @max, @min, and @sum.

查看更多
贪生不怕死
3楼-- · 2019-07-17 03:27
 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];
查看更多
登录 后发表回答