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

查看:44
本文介绍了避免“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 循环,当您删除一个对象时:- 减少索引变量并继续;.如果您在进入 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天全站免登陆