gpt4 book ai didi

objective-c - 用于在 NSMutableArray 崩溃中删除项目的快速枚举

转载 作者:行者123 更新时间:2023-12-04 02:52:17 25 4
gpt4 key购买 nike

我有一个奇怪的问题,如果我在 forin 枚举中删除我的项目,它会崩溃,就像这样:

for (Obstacle *obstacleToTrack in _obstaclesToAnimate) {
//this if else not so important for happening crash
if(obstacleToTrack.distance > 0){
obstacleToTrack.distance -= _playerSpeed * _elapsed;
}else{
if (obstacleToTrack.watchOut) {
obstacleToTrack.watchOut = NO;
}
obstacleToTrack.x -= (_playerSpeed + obstacleToTrack.speed) * _elapsed;
}
if (obstacleToTrack.x < -obstacleToTrack.width || _gameState == GS_OVER) {
[self removeChild:obstacleToTrack];
//this line makes crash happen , if remove this line code work fine
[_obstaclesToAnimate removeObject:obstacleToTrack];
}
}

如果我将代码更改为
NSMutableArray *forRemoving = [[NSMutableArray alloc]init];
for (Obstacle *obstacleToTrack in _obstaclesToAnimate) {
//this if else not so important for happening crash
if(obstacleToTrack.distance > 0){
obstacleToTrack.distance -= _playerSpeed * _elapsed;
}else{
if (obstacleToTrack.watchOut) {
obstacleToTrack.watchOut = NO;
}
obstacleToTrack.x -= (_playerSpeed + obstacleToTrack.speed) * _elapsed;
}
if (obstacleToTrack.x < -obstacleToTrack.width || _gameState == GS_OVER) {
// code change here
[self removeChild:obstacleToTrack];
[forRemoving addObject:obstacleToTrack];
}
}
for(Obstacle *obstacleToTrack in forRemoving){
[_obstaclesToAnimate removeObject:obstacleToTrack];
[forRemoving removeObject:obstacleToTrack];
}
[forRemoving release];

这会很完美,有人能告诉我为什么吗?

最佳答案

答案是,如果删除一个对象,则该数组中的其他对象会移动数组中的位置,因为删除了一个项目。

例如,我们有一个包含 4 个项目的数组,如果我们删除第一个项目(项目 0),以前位于索引 1 的项目现在位于索引 0,位于 2 的项目现在位于 1。
因此枚举中断。

您可以通过从计数到 0 循环遍历数组来解决此问题:

for (int i = [array count]-1; i >= 0; i--) {
id object = [array objectAtIndex:i];

if (some check) {
[array removeObjectAtIndex:i];
}
}

关于objective-c - 用于在 NSMutableArray 崩溃中删除项目的快速枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12950045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com