John
John

Reputation: 63

Filter title from core data

I have an entity that has title title and amount. I would like to display the total value I have for each title in my entity.

Upvotes: 1

Views: 73

Answers (3)

pbasdf
pbasdf

Reputation: 21536

The following will get the categories and the sum in one fetch operation:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Incoming"];
fetchRequest.resultType = NSDictionaryResultType;

NSExpression *sumExp = [NSExpression expressionWithFormat:@"sum:(amount)"];
NSExpressionDescription *sumED = [[NSExpressionDescription alloc] init];
sumED.name = @"sum";
sumED.expression = sumExp;
sumED.expressionResultType = NSDoubleAttributeType;

fetchRequest.propertiesToFetch = [@"title", sumED];
fetchRequest.propertiesToGroupBy = [@"title"];

NSArray *dictionaries = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];

See the NSExpression documentation here.

Upvotes: 0

Mundi
Mundi

Reputation: 80271

You can pretty much dispense with fetch requests by leveraging KVC (Key-Value-Coding).

First fetch (or filter) with this predicate:

[NSPredicate predicateWithFormat:@"category = %@", @"Food"];

Then just sum up the result in one line:

NSNumber *sum = [result valueForKeyPath:@"@sum.amount"];

There is no need to fetch only certain attributes using NSDictionaryResultType - just fetch the normal NSManagedObjects (Core Data will optimize for you).

Upvotes: 2

Rob Sanders
Rob Sanders

Reputation: 5367

You use NSPredicate to filter your objects by category and then you can fetch only the values of a certain property e.g.:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
// Entity
NSEntityDescription *ent = [NSEntityDescription entityForName:@"Incoming" inManagedObjectContext:context];
[request setEntity:ent];
// Predicate
NSPredicate *pred = [NSPredicate predicateWithFormat:@"category MATCHES[cd] %@", @"FOOD"];
[request setPredicate:pred];
// Property fetch
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:NO];
[request setPropertiesToFetch:@[@"Amount"]];

// Execute the fetch.
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
int total = 0;
if (objects) {
    for(NSDictionary *dict in objects) {
        NSString *key = dict.allKeys.lastObject;
        total += [dict[key] intValue];
    }
} else {
    NSLog(@"Fetch error: %@", error.localizedDescription);
}
NSLog(@"Total: %i", total);

Upvotes: 0

Related Questions