2011-12-10 83 views
7

我對obj-c比較陌生,所以我必須錯過某些東西,但是當敵人與牆壁碰撞時,我的程序會崩潰。我找到了從循環中移除敵人的位置,而在循環中,但對於我的生活,我無法弄清楚如何修復它。 我的代碼如下:集合<__ NSArrayM:0x76c11b0>在枚舉時發生了變異

(錯誤是 「[allEnemies的removeObject:enemyType1];」)

//始終運行 - (無效)更新:(ccTime)dt的 {

for (CCSprite *enemyType1 in allEnemies) { //for every attacking unit in allEnemies 

    //Adjust the collison box for each enemey depending on the height of the enemy 
    float a; 
    float b; 
    float yOne = (wall.contentSize.height-enemyType1.position.y); 
    float yTwo = (wall.contentSize.height); 
    float xTwo = 30; 
    a = (xTwo*(yOne/yTwo)); // always < 1 
    b = xTwo-a;    // always > 1 


    //Create the altered collison box 
    CGRect enemyType1Rect = CGRectMake (
       enemyType1.position.x - (enemyType1.contentSize.width/2), 
       enemyType1.position.y - (enemyType1.contentSize.height/2), 
       enemyType1.contentSize.width+b, 
       enemyType1.contentSize.height 
             ); 


    //If the enemey hits the wall, stop it, then add it to the attacking enemies array 
    if (CGRectIntersectsRect(enemyType1Rect, wall.boundingBox)) { 
     [enemyType1 stopAllActions]; 
     [allEnemies removeObject:enemyType1]; 
     [attackingEnemies addObject:enemyType1];    
    } 


} 
//Wall Collison END 

回答

24

好吧,就像錯誤狀態一樣,您在枚舉枚舉時突變了數組。最簡單的修復方法是做for (CCSprite *enemyType1 in [[allEnemies copy] autorelease])這樣你就可以枚舉數組的副本(這不會複製元素,只是給你另一個枚舉它們的容器),並且仍然可以修改可變數組。

枚舉時不能修改容器。

+0

好了,你能解釋正是做什麼。 [allEnemies copy]是否複製數組,並將其從原始「allEnemies」數組中移除。另外當你把「autorelease」放在那裏時,你不需要有「[allEnemies removeObject:enemyType1];」對?對不起,如果這聽起來真的很愚蠢(我剛剛得到了xcode 4,而且這還不是我3中的煩惱)。 編輯: 所以我改變了這段代碼,現在我得到: 無法註冊com.yourcompany.StromTheHouse與引導服務器。錯誤:未知的錯誤代碼。 – user1091516

+0

好吧,xcode討厭我。所以我想我得到了「for(CCSprite * enemyType1 in [[allEnemies copy] autorelease])」,我沒有得到引導程序錯誤,但現在當我嘗試在設備上測試時,出現一個新錯誤: StormTheHouse [11129:707] cocos2d:無法添加圖片:牆。png in CCTextureCache 2011-12-10 11:02:05.888 StormTheHouse [11129:707] ***聲明失敗 - [HelloWorld addChild:],/Users/rauhul/Desktop/Invasion/libs/cocos2d/CCNode.m: 385 2011-12-10 11:02:05.890 StormTheHouse [11129:707] ***終止應用程序由於未捕獲的異常'NSInternalInconsistencyException',原因:'參數必須是非零' – user1091516

+0

nvm這些帖子我想出了什麼是繼續,我在我的代碼中引用了wall.png,但圖像是WALL.png,Thx soooo – user1091516

4

問題在於以下代碼行中:[allEnemies removeObject:enemyType1]; 您正在枚舉數組allEnemies並在導致問題的相同枚舉中從數組中刪除對象。您應該使用臨時數組進行循環,同時實際上會變異(removeObject:)另一個數組。

0

此外,這可能會發生,當你添加一個對象到NSMutableArray中,並從該數組中讀取記錄。這兩個任務發生在兩個不同的線程中。就像一個正在後臺線程中發生,另一個正在主線程中發生。對線程也要小心。

2

迭代它時,您不能從NSMutableArray中刪除項目。

有幾種解決方案,以這樣的:

  • 迭代的數組的副本

  • 使用基於索引的for循環,而不是for each語法。

不是抄襲的陣列節省您的分配和幾個CPU週期:

for (int i = updatedLocalityArray.count-1 ; i >= 0 ; i--) 
{ 
    NSString *test = updatedLocalityArray[i]; 
    if ([test isEqualToString:tableViewCell.textLabel.text]) 
    { 
     [updatedLocalityArray removeObjectAtIndex:i]; 
     NSLog(@"%@ *****", updatedLocalityArray); 
    } 
} 
相關問題