如何解析NSMutable数组并添加值

时间:2012-02-27 19:45:58

标签: xcode ios5 for-loop nsmutablearray sum

我在尝试添加(总结)NSMutable数组中的所有值时遇到问题:ProfileItems包含来自Core Data Entity的数据,并填充了正确的数据。我只是在解析NSMutableArray并添加profileItems.songLength数据时遇到问题。

提前致谢

   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 个答案:

答案 0 :(得分:4)

尝试快速枚举,它将更快地运行并且需要更少的代码。

int sumOfSongs = 0;

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

答案 1 :(得分:0)

intValue对象上使用NSMutableArray函数,并使用%d打印整数。

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
    }

答案 2 :(得分:0)

尝试在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);
}