从NSMutableArray中删除对象 [英] Removing object from NSMutableArray

查看:90
本文介绍了从NSMutableArray中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在设置for循环时遇到了以下快捷方式(与我一直使用的教科书示例相比较):

  for(Item * i in items){...} 

  for(NSInteger i = 0; i <[items count]; i ++){...}这是正确的

如果我使用较短的版本,是否有办法删除当前迭代(即'i')?

您不能从数组中删除对象,而快速枚举 it:


计数是安全的 - 枚举器
有一个突变保护,以便如果
尝试在枚举期间修改集合
,一个异常是


无论如何,为什么需要在枚举时更改容器?考虑使用 removeObjectsInArray: removeObjectsAtIndexes:方法存储需要删除的元素并将其从容器中删除。 p>

I stumbled across the following shortcut in setting up a for loop (shortcut compared to the textbook examples I have been using):

for (Item *i in items){ ... }

As opposed to the longer format:

for (NSInteger i = 0; i < [items count]; i++){ ... } //think that's right

If I'm using the shorter version, is there a way to remove the item currently being iterated over (ie 'i')? Or do I need to use the longer format?

解决方案

You cannot remove objects from array while fast-enumerating it:

numeration is "safe"—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration, an exception is raised.

Anyway why do you need to change you container while enumerating it? Consider storing elements that need to be deleted and remove them from your container using removeObjectsInArray: or removeObjectsAtIndexes: method.

这篇关于从NSMutableArray中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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