2012-02-27 56 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); 
} 
相關問題