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

前端 未结 1 798
悲&欢浪女
悲&欢浪女 2021-01-20 04:48

Scenario:

I have an expense tracking iOS Application and I have a view controller called "DashBoardViewController" (table view controller - with FRC) which

相关标签:
1条回答
  • 2021-01-20 05:08

    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.

    0 讨论(0)
提交回复
热议问题