Jonathan Thurft
Jonathan Thurft

Reputation: 4173

How to get the Entity property from which an average is taken in CoreData

I've fetched some values from my CoreData Entity, Averaged and GroupedBy date the results. The query works great. Now... I've want to know the dates from which those results come from. The output shown is from the raw result. How could I make my query also spit out the date/GroupBy value (given that my GroupBy criteria is date) from which those averages where taken from

The output

(
        {
        averageWeight = 36;
    },
        {
        averageWeight = 22;
    }
)

The Code:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ExerciseData" inManagedObjectContext:context];
    [request setEntity:entity];

    // Specify that the request should return dictionaries.
    [request setResultType:NSDictionaryResultType];

    // Create an expression for the key path.
    NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"weight"];

    // Create an expression to represent the function you want to apply
    NSExpression *expression = [NSExpression expressionForFunction:@"average:"
                                                         arguments:@[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:@"averageWeight"];
    [expressionDescription setExpression:expression];
    [expressionDescription setExpressionResultType:NSInteger32AttributeType]; // For example, NSDateAttributeType

    // Set the request's properties to fetch just the property represented by the expressions.
    [request setPropertiesToFetch:@[expressionDescription]];
    request.predicate = [NSPredicate predicateWithFormat:@"exercise == %@",exercise];
    [request setPropertiesToGroupBy:[NSArray arrayWithObject:@"date"]];
    // Execute the fetch.
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    NSLog(@"%@",objects);

Upvotes: 0

Views: 146

Answers (1)

Martin R
Martin R

Reputation: 539965

Just add "date" as another property to fetch:

[request setPropertiesToFetch:@[expressionDescription, @"date"]];

Upvotes: 1

Related Questions