Paul S.
Paul S.

Reputation: 1352

How to parse through an NSMutable Array and add up the values

Im having problems trying to add (sum) up all the values in a NSMutable Array: The ProfileItems contains data from a Core Data Entity, and is populated with the correct data. I'm just having problems parsing through the NSMutableArray and adding up the profileItems.songLength data.

Thanks in advance

   ProfileItems *profileItems = [profileItemsNSMArray objectAtIndex:indexPath.row];

    //Renumber the rows
    int numberOfRows = [profileItemsNSMArray count];
    NSLog(@"numberofRows: %d", numberOfRows);

    for (int i = 0; i < numberOfRows; i++) 
    {
        int sumOfSongs = sumOfSongs + [[profileItems.songLength] objectAtIndex:i];

        NSLog(@"length: %@",sumOfSongs);
    }

Upvotes: 1

Views: 3142

Answers (3)

Parag Bafna
Parag Bafna

Reputation: 22930

use intValue function on NSMutableArray object and use %d for printing integer.

ProfileItems *profileItems = [profileItemsNSMArray objectAtIndex:indexPath.row];

    //Renumber the rows
    int numberOfRows = [profileItemsNSMArray count];
    NSLog(@"numberofRows: %d", numberOfRows);

    for (int i = 0; i < numberOfRows; i++) 
    {
        int sumOfSongs = sumOfSongs + [[[profileItems.songLength] objectAtIndex:i]intValue]; // use intValue

        NSLog(@"length: %d",sumOfSongs); //use %d for printing integer value
    }

Upvotes: 0

Bill Burgess
Bill Burgess

Reputation: 14154

Try fast enumeration, it will work much faster and requires much less code.

int sumOfSongs = 0;

for (ProfileItems *item in profileItemsNSMArray) {
   sumOfSongs = sumOfSongs + [item.songlength intValue]; // use intValue to force type to int
}

Upvotes: 4

tierfour
tierfour

Reputation: 682

Try casting the objects in the NSMutableArray:

ProfileItems *profileItems = (ProfileItems*)[profileItemsNSMArray objectAtIndex:indexPath.row];

int numberOfRows = [profileItemsNSMArray count];

for (int i = 0; i < numberOfRows; i++) 
{
    int sumOfSongs += [[profileItems.songLength] objectAtIndex:i];

    NSLog(@"length: %@",sumOfSongs);
}

Upvotes: 0

Related Questions