Removing object from NSMutableArray

2019-01-12 05:43发布

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?

5条回答
叛逆
2楼-- · 2019-01-12 06:10

I use this code for this:

for (NSUInteger i = [items count] - 1; ; i--) {
     [items removeObjectAtIndex:i];
}
查看更多
闹够了就滚
3楼-- · 2019-01-12 06:11

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).

查看更多
唯我独甜
4楼-- · 2019-01-12 06:14

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];
}
查看更多
小情绪 Triste *
5楼-- · 2019-01-12 06:20

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.

查看更多
太酷不给撩
6楼-- · 2019-01-12 06:22

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

for(id item in items) {
    if([item isEqual:itemToDelete]) {
        [items removeObject:item];
        break;
    }
}
查看更多
登录 后发表回答