Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing object from NSMutableArray

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?

like image 835
Ben Packard Avatar asked May 03 '10 09:05

Ben Packard


People also ask

What is NSMutableArray Objective C?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .


1 Answers

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.

like image 88
Vladimir Avatar answered Oct 17 '22 15:10

Vladimir