How to add sum of NSMutableArray

ios, nsmutablearray, objective-c

Solution

Simply remove this line from your Method and place it in `-viewDidLoad`.

NSMutableArray * scoreTally = [NSMutableArray array];

Advice : I noticed one thing in your code that you are using `for loop` to calculate the sum. There is one much better approach to calculate the sum of all the values inside an Array which is called KVC.

int sum = [scoreTally valueForKeyPath:@"@sum.self"];

The best part of KVC is that it is so simple and so easy to use and it reduces the number of lines code to a single line and hence the time.

Problem

Trying to tally up a score every time a kill is made and 5 points are added for each, however, it never adds the values and is thus stuck at 5 points even after additional kills are made. The following is my array code. ``` NSMutableArray * scoreTally = [NSMutableArray array]; NSNumber *scoreValue = [NSNumber numberWithInteger:5]; [scoreTally addObject:scoreValue]; int sum=0; for(int x=0; x < [scoreTally count]; x++) { sum += [[scoreTally objectAtIndex:x] intValue]; } NSLog(@"SUM %D",sum); score.text = [NSString stringWithFormat:@"Score: %d",sum]; ```

Original source