Created
October 29, 2010 05:11
-
-
Save tjboudreaux/652963 to your computer and use it in GitHub Desktop.
Getting the Average Value of a column in Core Data.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment