2012-02-27 83 views
1

我试图在NSMutable数组中添加(求和)所有值时出现问题:ProfileItems包含来自核心数据实体的数据,并且填充了正确的数据。我只是有问题解析通过NSMutableArray并添加profileItems.songLength数据。如何通过一个NSMutable数组解析并合计值

预先感谢

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

回答

4

尝试快速列举,它会工作得更快,需要更少的代码。

int sumOfSongs = 0; 

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

太棒了。我只需修改代码,但完美地工作。唯一缺少的是该项目前面的'*'。for(ProfileItems * item in profileItemsNSMArray){ – 2012-02-27 20:25:07

+0

完美。我更新了我的代码以防其他人遇到此答案。 – 2012-02-27 20:27:24

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 
    } 
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); 
} 
相关问题