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);