2011-10-11 83 views
3

我目前正在開發一款遊戲,需要真正快速枚舉數組。我需要每秒運行代碼30次,現在想問什麼是完成任務的最佳方式。 我想枚舉一個數組並同時對其進行修改。快速枚舉?

我知道2的時刻:

NSMutableArray*array; 

int i=0; 

int x=0; 
for (myclass*spr in [[array copy] autorelease]) { 
    if ([spr isInBounds]) { 
     //do something 
    } else { 
     [array removeObjectAtIndex:x]; 
     x--; 
    } 

    x++; 
} 

int x=0; 

while(x<[array count]) 
{ 
    if(![(myclass*)spr isInBounds]) { 
     [array removeObjectAtIndex:x]; 
     x--; 
    } 
    x++; 
} 

什麼是做到這一點的最快方法?你知道其他方法嗎? 感謝您的幫助!

回答

6

在你的具體情況下,最好的辦法可能是在NSIndexSet之外保存你不關心的對象的索引,並在循環之後使用它們來一次刪除所有對象。

NSMutableIndexSet *is = [NSMutableIndexSet indexSet]; 
[array enumerateObjectsUsingBlock:^(myclass *spr, NSUInteger idx, BOOL *stop) { 
    if ([spr isInBounds]) { 
     // do something 
    } else { 
     [is addIndex:idx]; 
    } 
}]; 
[array removeObjectsAtIndexes:is]; 
+0

謝謝!這是我一直在尋找的東西! – user610246