Joining tables in Core Data - objective-c

I have been trying to solve the following problem using Core Data without any luck.
My model has two entities:Group and Element. Both with a "name" attribute and a to-many relationship in the form of: "group.elements" and "element.groups" (a Element belonging to several Groups and a Group having several Elements)
I want to establish a "filter" in the form of:
elements that belongs to "group_A" AND "group_B"
In order to show to the user something like:
The elements that match the filter belong to this set of groups in that quantity
As an example, having something like:
Element_1 Group_A, Group_B, Group_C
Element_2 Group_B, Group_C
Element_3 Group_A, Group_B, Group_D
Element_4 Group_A, Group_B, Group_D
Element_5 Group_C, Group_D
The answer should be: Element_1, Element_3 and Element_4 match the filter and the information to be shown would be like:
Group_A has 3 elementsGroup_B has 3 elementsGroup_C has 1 elementGroup_D has 2 elementsThat match the filter
How could I put this in Core Data NSExpression, NSPredicate etc.?
Thanks.
UPDATE
I think I found two ways of solving this.
Option 1
This option establishes an NSArray with the "group's names filter" and returns all the groups with the number of elements they have that match the condition EVEN THOUGH it's zero (no elements match)
There are two entities, "Grp" and "Elem", with a to-many relationship between them.
NSError *error = nil;
// Properties to be fetched
NSPropertyDescription *namePropDesc = [[[[self.moModel entitiesByName] objectForKey:#"Grp"] propertiesByName] objectForKey:#"name"];
// Variable group filter
NSArray *grpFilter = [NSArray arrayWithObjects:#"group_A", #"group_B", nil];
// Expression for counting elements
NSExpressionDescription *countExprDesc = [[NSExpressionDescription alloc] init];
[countExprDesc setExpression:[NSExpression expressionWithFormat:#"SUBQUERY(elems,$elem, SUBQUERY($elem.grps, $grp, $grp.name in %#).#count==%d).#count", grpFilter, grpFilter.count]];
[countExprDesc setExpressionResultType:NSInteger32AttributeType];
[countExprDesc setName:#"elementCount"];
// Create data fetching and set its properties
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Grp"];
[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:[NSArray arrayWithObjects:namePropDesc,countExprDesc, nil]];
NSArray *results = [self.moContext executeFetchRequest:request error:&error];
NSLog(#"results = %#"results);
Option 2
This option establishes an NSArray with the "group's names filter" and returns all the groups with the number of elements they have that match the condition WITHOUT THOSE groups that don't have any elements.
In this case, I created three entities, Grp, Elem and RGE. Having RGE as an intermediate entity that keeps the to-many relationships with the two other. This option allows to put some extra information in the group-element association (creation date, etc.) if needed. Grp and Elem don't have a relationship between each other.
Note: In fact, I neened to create a "regular" field (name) in the RGE entity to apply the #count function. If a "to-many relationship field" is used it fails to count properly.
NSError *error = nil;
// Variable group filter
NSArray *grpFilter = [NSArray arrayWithObjects:#"group_A", #"group_B", nil];
// Create variable predicate string from "group's names filter"
NSMutableString *predicateStr = [[NSMutableString alloc] init];
for(int n=0;n<grpFilter.count;n++) {
if(n>0) {
[predicateStr appendString:#" AND "];
}
[predicateStr appendString:#"(ANY elem.rges.grp.name=%#)"];
}
// Filter to be applied
NSPredicate *filterQuery = [NSPredicate predicateWithFormat:predicateStr argumentArray:grpFilter];
// Expression for counting elements
NSExpressionDescription *countExprDesc = [[NSExpressionDescription alloc] init];
[countExprDesc setExpression:[NSExpression expressionWithFormat:#"name.#count"]];
[countExprDesc setExpressionResultType:NSInteger64AttributeType];
[countExprDesc setName:#"count"];
// Expression for grouping JUST by the group's name
NSExpressionDescription *grpNameExprDesc = [[NSExpressionDescription alloc] init];
[grpNameExprDesc setExpression:[NSExpression expressionWithFormat:#"grp.name"]];
[grpNameExprDesc setExpressionResultType:NSStringAttributeType];
[grpNameExprDesc setName:#"grpName"];
// THIS COULD JUST BE an NSPropertyDescription if you want the WHOLE "grp":
NSPropertyDescription *grpPropDesc = [[[[self.moModel entitiesByName] objectForKey:#"RGE"] propertiesByName] objectForKey:#"grp"];
// Create data fetching and set its properties
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"RGE"];
[request setResultType:NSDictionaryResultType];
[request setPropertiesToGroupBy:[NSArray arrayWithObjects: grpNameExprDesc, nil]];
[request setPropertiesToFetch:[NSArray arrayWithObjects:grpNameExprDesc, countExprDesc, nil]];
[request setPredicate:filterQuery];
NSArray *results = [self.moContext executeFetchRequest:request error:&error];
NSLog(#"results = %#",results);

I had a similar problem and I solved it using the "option 2" approach: Grouping three entities with many-to-many relationships
Regards.
Pedro Ventura.

I fetched all the groups, and for the display I did the following:
Group *gr = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSSet *filtered = [NSSet set];
if ([gr.name isEqualToString:#"GroupA"]) {
filtered = [gr.elements filteredSetUsingPredicate:
[NSPredicate predicateWithFormat:#"any groups.name == %#", #"GroupB"]];
}
else if ([gr.name isEqualToString:#"GroupB"]) {
filtered = [gr.elements filteredSetUsingPredicate:
[NSPredicate predicateWithFormat:#"any groups.name == %#", #"GroupA"]];
}
else {
filtered = [gr.elements filteredSetUsingPredicate:
[NSPredicate predicateWithFormat:
#"any groups.name == %# && any groups.name == %#",
#"GroupA", #"GroupB"]];
}
cell.textLabel.text =
[NSString stringWithFormat:#"%# has %d elements.",
gr.name, filtered.count] ;
This gives the correct counts as in your example. However, if there is an excluded group, it would still be listed with 0 elements.

Related

Filtering many-to-many count expression using existing subquery

In my app, I have a many-to-many relationship between tags and links as follows :
Tags <<-->> Links
I am trying to return a list of the tags that relate to links that have the currently active tags, but are not included in the active tags.
I also want to obtain a count of the number of links that have the 'other' tags, which needs to be limited by the active tags.
Using the below, I have been able to return the 'other' tags and a count of links, but the count returned is of all links for each tag.
I would like to be able to count the links using a similar approach to the one I'm using to build the subquery, but am struggling to get it to work. I have tried using the subquery generated in the count NSExpression, but this errors when the subquery is evaluated.
// Test array of tag names
self.activeTagArray = [#[#"tag1", #"tag2"] mutableCopy];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[Tag entityName]];
// We want to exclude the tags that are already active
NSPredicate *activeTagsPredicate = [NSPredicate predicateWithFormat:#"NOT ANY name IN %#", self.activeTagArray];
// Build subquery string to identify links that have all of the active tags in their tag set
NSString __block *subquery = #"SUBQUERY(links, $link, ";
[self.activeTagArray enumerateObjectsUsingBlock:^(id tagName, NSUInteger index, BOOL *stop) {
if (index == self.activeTagArray.count - 1) {
subquery = [subquery stringByAppendingString:[NSString stringWithFormat:#"SUBQUERY($link.tags, $tag, $tag.name = '%#') != NULL", tagName]];
} else {
subquery = [subquery stringByAppendingString:[NSString stringWithFormat:#"SUBQUERY($link.tags, $tag, $tag.name = '%#') != NULL AND ", tagName]];
}
}];
subquery = [subquery stringByAppendingString:#") != NULL"];
NSLog(#"Subquery : %#", subquery);
NSPredicate *noTagsPredicate = [NSPredicate predicateWithFormat:subquery];
// Create a predicate array
NSArray *predicateArray = #[noTagsPredicate, activeTagsPredicate, userPredicate];
NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicateArray];
fetchRequest.predicate = compoundPredicate;
fetchRequest.relationshipKeyPathsForPrefetching = #[#"links"];
// Set up the count expression
NSExpression *countExpression = [NSExpression expressionForFunction: #"count:" arguments:#[[NSExpression expressionForKeyPath: #"links.href"]]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
expressionDescription.name = #"counter";
expressionDescription.expression = countExpression;
expressionDescription.expressionResultType = NSInteger32AttributeType;
fetchRequest.propertiesToFetch = #[#"name", expressionDescription];
// Sort by the tag name
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
fetchRequest.sortDescriptors = #[sortDescriptor];
fetchRequest.resultType = NSDictionaryResultType;
NSError *error = nil;
NSArray *resultsArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(#"Error : %#", [error localizedDescription]);
}
NSMutableArray *allTags = [[NSMutableArray alloc] init];
for (NSDictionary *tagDict in resultsArray) {
NSLog(#"Tag name : %#, Link Count : %#", tagDict[#"name"], tagDict[#"counter"]);
[allTags addObject:tagDict[#"name"]];
}
[allTags addObjectsFromArray:self.activeTagArray];
Any help with this would be greatly appreciated!
If I understand your question correctly, the following predicate fetches your "other tags",
i.e. all tags that are related to a link which is related to all of the given "active tags":
NSArray *activeTags = #[#"tag1", #"tag2"];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Tag"];
NSPredicate *p1 = [NSPredicate predicateWithFormat:#"NOT name in %#", activeTags];
NSPredicate *p2 = [NSPredicate predicateWithFormat:#"SUBQUERY(links, $l, SUBQUERY($l.tags, $t, $t.name IN %#).#count = %d).#count > 0",
activeTags, [activeTags count]];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:#[p1, p2]];
[request setPredicate:predicate];
And now the "trick": The left hand side of the predicate p2 is
SUBQUERY(links, $l, SUBQUERY($l.tags, $t, $t.name IN %#).#count = %d).#count
and that is exactly the count of links that should be included in the result,
so we can create the expression description from that predicate:
NSExpression *countExpression = [(NSComparisonPredicate *)p2 leftExpression];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
expressionDescription.name = #"counter";
expressionDescription.expression = countExpression;
expressionDescription.expressionResultType = NSInteger32AttributeType;
[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:#[#"name", expressionDescription]];
The resulting SQLite query is quite complex. It might be sensible to fetch the links first:
NSFetchRequest *linkRequest = [NSFetchRequest fetchRequestWithEntityName:#"Link"];
NSPredicate *linkPredicate = [NSPredicate predicateWithFormat:#"SUBQUERY(tags, $t, $t.name IN %#).#count = %d",
activeTags, [activeTags count]];
[linkRequest setPredicate:linkPredicate];
NSArray *activeLinks = [context executeFetchRequest:linkRequest error:&error];
and fetch the tags in a separate step, which can be done with above code where only the
predicate p2 is replace by the simpler subquery
NSPredicate *p2 = [NSPredicate predicateWithFormat:#"SUBQUERY(links, $l, $l IN %#).#count > 0", activeLinks];

Objective-c. Fetching distinct values of attribute from core data

i have run into a problem that i can not solve. I have a "database" - read core data - where i have attribute that holds a value and level.
Something like that
value -------- level
55 -------------4
33 -------------4
50 -------------5
70 -------------6
44 -------------5
what i want now is a to extract all values from level 5 only and add them together. How can i achieve this ?I did found "fetch distinct values" on apple dev site, but this would apply to extracting all values from one attribute.
Help appreciated, thank you. If i have missed a similar topic then please provide me with a link. Thanks
You can use the following fetch request:
// Fetch request for your entity:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Entity"];
[request setResultType:NSDictionaryResultType];
// Restrict result to "level == 5":
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"level == %d", 5];
[request setPredicate:predicate];
// Expression description for "#sum.value":
NSExpression *sumExpression = [NSExpression expressionForKeyPath:#"#sum.value"];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:#"sumValue"];
[expressionDescription setExpression:sumExpression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];
[request setPropertiesToFetch:#[expressionDescription]];
NSArray *result = [context executeFetchRequest:request error:&error];
The result for your data is
(
{
sumValue = 94;
}
)
i.e. an array containing one dictionary with the sum of values with level=5.

Show distinct results in fetch request, group by an attribute and calculate the total for that attribute

Scenario:
I have an expense tracking iOS Application and I have a view controller called "DashBoardViewController" (table view controller - with FRC) which would basically categorize my expenses/incomes for a given week, a month, or year and display it as the section header title for example : (Oct 1- Oct 7, 2012) and it shows expenses/incomes ROWS and related stuff according to that particular week or month or year.
My Question:
What I want to accomplish is :
Suppose I save 3 new expenses with SAME category named "Auto" on three different dates(11 nov, 14 nov, 16 nov, 2012 respectively).
In my view controller, I want to display that category "Auto" as a row in table view but it should appear only as ONE ROW and NOT THREE TIMES as I saved three expenses (with category "Auto") and the total amount should be added up for all the 3 expenses I saved (for that particular category). Something like the following screenshot.
I have written some code bit it gives me THREE ROWS for the SAME CATEGORY and not what I actually want (ONE ROW for SAME CATEGORY) and I don't know how I would calculate the total for them? Should be something related to NSPredicate here or fetched results controller.
Any help would be highly appreciated.
- (void)userDidSelectStartDate:(NSDate *)startDate andEndDate:(NSDate *)endDate
{
AppDelegate * applicationDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
NSManagedObjectContext * context = [applicationDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Money" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
NSPredicate *predicateDate = [NSPredicate predicateWithFormat:#"(date >= %#) AND (date <= %#)", startDate, endDate];
// Edit the sort key as appropriate.
typeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"type" ascending:YES]; // type refers to an expense or income.
dateSortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:YES];
if(self.choiceSegmentedControl.selectedIndex == 0) // UISegment Control for "Sorting Category"
{
NSPredicate *predicateCategory = [NSPredicate predicateWithFormat:#"cat == %#", #""];
NSArray * subPredicates = [NSArray arrayWithObjects:predicateCategory, predicateDate, nil];
NSPredicate * compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
[fetchRequest setPredicate:compoundPredicate];
choiceSortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"cat" ascending:NO];
}
NSArray * descriptors = [NSArray arrayWithObjects:typeSortDescriptor, dateSortDescriptor, choiceSortDescriptor, nil];
[fetchRequest setSortDescriptors:descriptors];
[fetchRequest setIncludesSubentities:YES];
if(_fetchedResultsController)
{
[_fetchedResultsController release]; _fetchedResultsController = nil;
}
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:#"type" cacheName:nil];
_fetchedResultsController.delegate = self;
NSError *anyError = nil;
if(![_fetchedResultsController performFetch:&anyError])
{
NSLog(#"error fetching:%#", anyError);
}
__block double totalAmount = 0;
[[self.fetchedResultsController fetchedObjects] enumerateObjectsUsingBlock: ^void (Money *money, NSUInteger idx, BOOL *stop) {
totalAmount += [[money amount] doubleValue];
}];
[fetchRequest release];
//Finally you tell the tableView to reload it's data, it will then ask your NEW FRC for the new data
[self.dashBoardTblView reloadData];
self.startDate = startDate;
self.endDate = endDate;
}
I thought to use NSDictionaryResultType but that's giving a problem with the FRC i have used ( for section names, filling up the table view etc.)
The code where I loop through the FRC gives me the total amount (for income and expenses) BUT I want the total amount for each category (example: total for category "Auto", total for category "Entertainment"). Please help me, I am totally stucked up here.
I don't think you can massage your FRC into returning the kind of objects you need. NSPredicate just filters the kind of objects to return it does not create new ones from the data.
However, you can fetch the your money objects filtered by the date and then calculate the data from the array of money objects using KVC Collection Operators like so:
NSArray *moneyObjectsFilteredbyDate = [self.fetchedResultsController fetchedObjects]
NSArray *categoryStrings = [moneyObjectsFilteredbyDate valueForKeyPath:#"#distinctUnionOfObjects.cat"];
NSArray *sortedCategoryStrings = [categoryStrings sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSMutableArray *aggregatedDataObjects = [NSMutableArray array];
for (NSString *aCategoryString in sortedCategoryStrings) {
NSPredictate *categoryPredicate = [NSPredicate predicateWithFormat:#"cat == %#", aCategoryString];
NSArray *moneyWithThisCategory = [moneyObjectsFilteredByDate filteredArrayUsingPredicate:categoryPredicate];
NSNumber *sum = [moneyWithThisCategory valueForKeyPath:#"#sum.amount"];
[aggregatedDataObjects addObject:#{#"category" : aCategoryString, #"sum" : sum, #"individualExpenses" : moneyWithThisCategory}];
}
Of course, you could do parts of the in the method where you configure the table cell (like calculating the sum itself), but I hope it gives you an idea. But I don't think you can use the predicate in a form of an SQL query or similar to create new data structure.
Something else you could do: Make the category an individual object of your Core Data model and add a relationship between moneyobjects and Category objects. Then you can just fetch category objects. Although you would then have to filter the expense for a category by the dates.

NSPredicate always gives back the same data

I am trying to work with NSPredicates. But it always give me back the same array. Here you can see my predicate.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"whichAlbum.album_id == %d", AlbumId];
[request setEntity:[NSEntityDescription entityForName:#"Picture" inManagedObjectContext:self.genkDatabase.managedObjectContext]];
[request setPredicate:predicate];
Also when I try it hardcoded. It gives back the same array.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"whichAlbum.album_id == 5"];
My database model is:
And here you can see how I put data in my database for entity Picture.
+ (Picture *)pictureWithGenkInfo:(NSDictionary *)genkInfo
inManagedObjectContext:(NSManagedObjectContext *)context
withAlbumId:(int)albumId
withPictureId:(int)pictureId;
{
Picture *picture = nil;
picture = [NSEntityDescription insertNewObjectForEntityForName:#"Picture"
inManagedObjectContext:context];
picture.url = [genkInfo objectForKey:PICTURES_URL];
picture.pic_album_id = [NSNumber numberWithInt:albumId];
picture.picture_id = [NSNumber numberWithInt:pictureId];
return picture;
}
Anybody can help me ?
Kind regards
EDIT
for (NSDictionary *genkInfo in albums ) {
albumId++;
Album *album = [Album albumWithGenkInfo:genkInfo inManagedObjectContext:document.managedObjectContext withAlbumId:albumId];
for (NSDictionary *genkInfo2 in pictures ) {
pictureId++;
Picture *pic = [Picture pictureWithGenkInfo:genkInfo2 inManagedObjectContext:document.managedObjectContext withAlbumId:albumId withPictureId:pictureId];
[album addPicturesObject:pic]; // this method should be automatically generated
}
pictureId = 0;
// table will automatically update due to NSFetchedResultsController's observing of the NSMOC
}
Better, assuming the value for AlbumId is some kind of number primitive:
old style:
[NSPredicate predicateWithFormat:#"whichAlbum == %#", [NSNumber numberWithInt:AlbumId]];
modern style: (xcode 4.5)
[NSPredicate predicateWithFormat:#"whichAlbum == %#", #(albumId)];
As it looks like predicateWithFormat: might only generate proper predicates with %# and #K in its format strings.
Best: Assuming you have access to the Album managed object you are trying to match try this:
[NSPredicate predicateWithFormat:#"whichAlbum == %#", album];
Match to the object, not one of its properties
just remove whichAlbum and try:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"album_id == %d", AlbumId];

Number of elements in NSArray where (....)

I am used to working in C# using the linq extensions (list.select(...).where(...) ext), and I was wondering if there was some way of doing the same sort of thing in Objective-C. This would save me from building a number of rather complicated queries using Core Data, which is great for some things, but perhaps not the best for complex queries (or maybe I'm just uninformed).
Is there some kind of equivalent for linq in Objective-C/Core Data?
EDIT: More specifically, I would like to count the number of elements that fit some criteria. Say my model has a field called date. I am trying to select the distinct dates, and then calculate how many of each date there are. In SQL this would be like a group by, and a COUNT aggregate.
Your question goes from very general ("linq equivalent?") to very specific (computing count by date). I'll just answer your specific question.
Unfortunately, NSArray doesn't have a built-in map or select method, but it does offer NSCountedSet, which will compute what you want:
NSCountedSet *dateSet = [NSCountedSet set];
for (id thing in array) {
[dateSet addObject:[thing date]];
}
for (NSDate *date in dateSet) {
NSLog(#"There are %d instances of date %#", [dateSet countForObject:date], date);
}
Change predicate , and "Date" keys with your props
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"child" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:#"Date"]];
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"(start <= %# ) and (completion < 100)",sda ];
[fetchRequest setPredicate:predicate];
int c = [self.managedObjectContext countForFetchRequest:fetchRequest error:nil];
Here was something posted with comes close
filtering NSArray into a new NSArray in objective-c
Anyway AFAIK you don't have some sort of linq in Objective-C but you have. Arrays and Blocks. And Blocks are functions. So you can really filter on anything in there.
Of course, Cora Data has many functions to make complex queries:
In example to get sum of elements, you have two major ways:
first - get your data to NSSet or NSArray and use #sum operator:
//assume that `childs` are NSArray of your child entities and ammount is attribute to sum, and has attributes start (date) and completion (integer)
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"child" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"(start <= %# ) and (completion < 100)", dzis];
[fetchRequest setPredicate:predicate];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
NSError *error = nil;
if ([afetchedResultsController performFetch:&error]) {
NSArray *childs = afetchedResultsController.fetchedObjects;
NSNumber *sum=[childs valueForKeyPath:"#sum.ammount"];
}
second is using specific fetch for specific value with added NSExpressionDescription with a sum. This way is harder but better for larger db's
suppose if you have an array of your model objects, you could that with the following statement,
NSArray *distintDatesArray = [array valueForKeyPath:#"#distinctUnionOfObjects.date"];
for ( NSDate *date in distintDatesArray)
{
NSLog (#"Date :%# ,count : %d",date,[[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"date = %#",date]] count]);
}
This will have same effect as the group by query.