枚举时,Objective-C NSMutableArray突变了吗? [英] Objective-C NSMutableArray mutated while being enumerated?

查看:89
本文介绍了枚举时,Objective-C NSMutableArray突变了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点偶然发现了一个错误,您尝试从NSMutableArray中删除对象,而其他对象正在其他位置添加到该对象中.为了简单起见,我不知道如何解决它.这是我在做什么:

I kinda stumbled into the error where you try to remove objects from an NSMutableArray while other objects is being added to it elsewhere. To keep it simple, i have no clue on how to fix it. Here is what i'm doing:

我有4个计时器,它们调用4种不同的方法,这些方法将一个对象添加到同一数组中.现在,当我按下某个按钮时,我需要删除数组中的所有对象(或至少某些对象).因此,我尝试首先使所有4个计时器无效,然后使用数组完成我想要的工作,然后启动计时器.我以为这会行得通,因为我不再使用计时器来枚举整个数组,但是看来这是行不通的.

I have 4 timers calling 4 different methods that adds an object to the same array. Now, when i press a certain button, i need to remove all objects in the array (or at least some). So i tried to first invalidate all the 4 timers, and then do the work i want with the array, and then fire up the timers. I thought this would've worked since i am not using the timers anymore to enumerate through the array, but seemingly it doesn't work.

这里有什么建议吗?

推荐答案

与您的计时器无关.因为(我假设)您的计时器都与您的修改方法在同一线程上工作,所以您无需停止和启动它们. iOS不会使用计时器中断的中断模型,它们必须像其他任何事件一样等待轮到:)

It's nothing to do with your timers. Because (I assume) your timers are all working on the same thread as your modifying method you don't need to stop and start them. iOS doesn't use an interrupt model for timer callbacks, they have to wait their turn just like any other event :)

您可能正在做类似的事情

You're probably doing something like

for (id object in myArray)
   if (someCondition)
       [myArray removeObject:object];

在浏览可变数组时,您无法对其进行编辑,因此您需要创建一个临时数组来保存要删除的内容

You can't edit a mutable array while you're going through it so you need to make a temporary array to hold the things you want to remove

// Find the things to remove
NSMutableArray *toDelete = [NSMutableArray array];
for (id object in myArray)
   if (someCondition)
       [toDelete addObject:object];

// Remove them
[myArray removeObjectsInArray:toDelete];

这篇关于枚举时,Objective-C NSMutableArray突变了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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