Search code examples
objective-cnsdecimalnumber

What's the correct way to accumulate NSDecimalNumber values?


I am trying to accumulate NSDecimalNumber values obtained from an array (apptDataArray, obtained from a CoreData store; aCurrentCharges is defined as NSDecimalNumber). This is my code:

        NSDecimalNumber *accumulatedFees = 0;
        for(int i = 0; i < apptDataArray.count; i++)  {
            AppointmentInfo *currentAppointment = [apptDataArray objectAtIndex: i];
            accumulatedFees = [accumulatedFees decimalNumberByAdding: currentAppointment.aCurrentCharges];  //  <----  not accumulating
        }
        oAccumulatedCharges.text = [NSString stringWithFormat:@"%@",accumulatedFees];

My problem is the line marked not accumulating is doing just that -- not accumulating. What am I doing wrong?


Solution

  • The variable accumulatedFees is not being initialized correctly. Try setting it this way:

    NSDecimalNumber *accumulatedFees = [NSDecimalNumber zero];