1

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

3 Answers 3

4

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome. I just had to touch up the code, but works perfectly. The only thing missing was the '*" in front of the item. for (ProfileItems *item in profileItemsNSMArray) {
Perfect. I updated my code in case anyone else comes across this answer.
0

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

Comments

0

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
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.