Removing object from NSMutableArray

蓝咒 提交于 2019-11-27 15:28:31
Vladimir

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.

RaiderF

Just add keyword break; after removing the item...

for(id item in items) {
    if([item isEqual:itemToDelete]) {
        [items removeObject:item];
        break;
    }
}

An Objective-C collection must not be modified during enumeration.

You may use this variant to delete objects from collection:

for (NSInteger i = items.count - 1; i >= 0 ; i--) {
   [items removeObjectAtIndex:i];
}

The former loop is a "for-each" loop in Objective C.

*i is a pointer to the direct item in the items-Array (most of the time this will be NSMutableArray).

This way you can operate directly on the item:

[items removeObject: i];

This (should) work - I am currently not working on my Mac and can't check it. However it might be that Objective-C Prevents removing objects while iterating over the collection (that is quite common in most languages).

slava

I use this code for this:

for (NSUInteger i = [items count] - 1; ; i--) {
     [items removeObjectAtIndex:i];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!