2010-10-18 97 views
1

如果我有以下NSManagedObject,我怎样才能得到number1的值的平均值和number2的值的平均值?如何获得具有核心数据的列的平均值?

@interface Log : NSManagedObject 
{ 


} 


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

感谢:d

回答

6
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]; 
1

使用集合操作@avg

比方说,您已经为您的Log对象提取了一个对象并将结果NSSet存储在logs中。然后,你可以简单地说:

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

@avg是,你可以在关键路径集合使用运营商的极少数之一。其他一些是@max,@min@sum