Summarize CoreData attribute

I'm just starting to program on iOS, so thank you very much for your patience and help in advance. I am an Expense object with an attribute (float) called "value". I have a tableView with a filled coreData form with NSFetchedResultsController. I'm trying to show in the label (or table heading) the total amount of "values" of all my "Expenses", but I canโ€™t implement the solution after reading Apple Docs and googling in different forums. Of course, a novice disorientation. Evaluate any guidance on the best way to implement this king of operations or any code that shows a similar solution.

+3
source share
1 answer

primarily. You must use Decimal (the primary data name for nsdecimalnumber) and NSDecimalNumber if you want to calculate and save the currency. I executed the code you need with float. But you must really change it to NSDecimalNumber. Read this to find out why you should do this.

If you want to add an expense value to the section heading, this is easy. You basically take care of the costs of all the objects in the section and summarize them.

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    float expense = 0;
    for (NSManagedObject *object in [sectionInfo objects]) {
        expense += [[object valueForKey:@"expense"] floatValue];
    }
    return [NSString stringWithFormat:@"%@ [Expense: %f]", [sectionInfo name], expense];
}

Even if you do not use partitions in your table, this will work. But you have to change the returned string.

I think you should be able to understand this. There is also a more general way to do this. I wrote you a little more detailed for you. It uses 3 lines instead of 1 in the for-loop, but does the same.

float expense = 0;
for (NSManagedObject *object in [self.fetchedResultsController fetchedObjects]) {
    NSNumber *objectExpenseNumber = [object valueForKey:@"expense"];
    float objectExpense = [objectExpenseNumber floatValue];
    expense = expense + objectExpense;
}
NSLog(@"Expense: %f", expense);

Not much to explain.

edit: , NSDecimalNumber

NSDecimalNumber *expense = [NSDecimalNumber decimalNumberWithString:@"0"];
for (NSManagedObject *object in [self.fetchedResultsController fetchedObjects]) {
    NSDecimalNumber *objectExpenseNumber = [object valueForKey:@"expense"];
    expense = [expense decimalNumberByAdding:objectExpenseNumber];
}
NSLog(@"Expense: %@", expense);
+8

Source: https://habr.com/ru/post/1787295/


All Articles