避免“NSArray在被枚举时被突变” [英] Avoiding "NSArray was mutated while being enumerated"

查看:156
本文介绍了避免“NSArray在被枚举时被突变”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSMutableArray 存储用于Box2d物理模拟的鼠标点。当使用多个手指来玩时,我会得到例外

I have an NSMutableArray that stores mousejoints for a Box2d physics simulation. When using more than one finger to play I'll get exceptions stating


NSArray在枚举时发生了变化

NSArray was mutated while being enumerated

我知道这是因为我从数组中删除对象,同时枚举它,使枚举无效。

I know this is because I'm deleting objects from the array while also enumerating through it, invalidating the enum.

我想知道的是什么是最好的策略来解决这个问题?我已经在线看到了一些解决方案: @synchronized ,复制数组之前枚举或将接头放入一个垃圾数组,以备以后删除(我不知道工作,因为我需要删除鼠标从数组直接删除它从世界)。

What I want to know is what is the best strategy to solve this going forward? I've seen a few solutions online: @synchronized, copying the array before enumerating or putting the touch joint into a garbage array for later deletion (which I'm not sure would work, because I need to remove the mousejoint from the array straight after removing it from the world).

推荐答案

您可以随时迭代没有枚举器。
这意味着一个常规的 for 循环,当你删除一个对象时: - 递减索引变量和 continue;
如果你在进入for循环之前缓存数组的计数,那么确保在删除对象时减少数组。

You can always iterate without an enumerator. Which means a regular for loop, and when you remove an object:- decrement the index variable and continue;. if you are caching the array's count before entering the for-loop, then make sure you decrement that too when removing an object.

无论如何,我不看看为什么具有对象的数组以后的删除将是一个问题。我不知道你所拥有的确切情况和涉及的技术,但理论上应该不会有问题。
因为在大多数情况下使用这种方法,你可以在第一次枚举中不做任何事情,并在枚举删除数组时做真正的工作。
如果你有一个情况,在第一次枚举你再次检查一些对同一个数组,并且你需要知道对象不再有,你可以只添加一个检查以查看它们是否在删除数组中。

Anyway, I do not see why an array with objects for later removal would be a problem. I do not know the exact situation which you are having and the technologies involved, but theoretically there should not be a problem. Because in most cases when using this method you can just do nothing in the first enumeration, and do the real work when enumerating the removal array. And if you have a situation where in the first enumeration you are checking something again against the same array and you need to know that the objects are not there anymore, you can just add a check to see if they are in the removal array.

无论如何,希望我帮助。
祝你好运!

Anyway, hope I helped. Good luck!

这篇关于避免“NSArray在被枚举时被突变”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆