Search code examples
xcodeuitableviewcore-datansfetchedresultscontrollernsfetchrequest

Core Data. Is it possible creating a view like you would do with normal SQL


In normal SQL world you would use Create View .... to define a view on one or more tables, e.g. to get a join and already a group by. Is that also possible somehow in Core data?

The reason I'm asking is, I have a table with a details. Each detail record has two keys and an amount. Now I need to show the sum of the amounts grouped by the two keys in a table view - i.e. The first key in the section and the second as normal entry with the sum amount. I thought FRC would work, but it does not group (add up the detail records). With a normal fetch request I can group and get everything - but it seems to be a lot of work to handle the sections manual. So I thought, the best is, I put a view on the table and use the FRC to bring it in the table view. Does that make sense? Any help ist very much appreciated.

example:

I have three fields:
A X  2
A X  2
A Z  3
B X  2
B Y  2
B Y  1
B Z  8

as a result I need

 Section : A
 X 4
 Z 3
 Section: B
 Y 2
 Z 8

Solution

  • So I am not sure if there is a shorter answer but here's how you can do it. I'll assume the first column, second column and third column are called: firstCol, secondCol, thirdCol.

    You can use this predicate to get all object for "A" and put it in resultArray:

    //loop over the letters A to Z. Here's what it would look like:
    NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"firstCol = %@)", @"A"];
    

    Then find all the second column letters for objects that have A in first column (resultArray):

    NSArray *allLetters = [resultArray valueForKeyPath:@"@distinctUnionOfObjects.secondCol"];
    

    In case of "A" allLetters will include X and Z. Then loop over allLetters and add up the third column:

    For (NSString *letter in allLetters) {
       int sum = [allLetters valueForKeyPath:[NSString stringWithFormat:@"@sum.%@", letter]];
       //this sums up each letter for example returns 4 for X in case of "A"
       //insert the sum in an Array and then a Dictionary that can be used for data source of the table.
    }