On Nov 30, 2009, at 2:45 PM, Dennis Munsie wrote: > I run into this all the time where I need to iterate through an > NSMutableArray (or set, etc, etc) and remove some of the items. My normal > pattern has been this: > > NSMutableSet *removeSet = [[NSMutableSet alloc] init]; > for(NSObject *foo in myArray) { > if(needToRemoveFoo) { > [removeSet addObject:foo]; > } > } > for(NSObject *foo in removeSet) { > [myArray removeObject:foo]; > } > [removeSet release];
Some alternatives: * Iterate over the array just using an index, rather than fast enumeration (or NSEnumerator). Then, you can mutate the array as you go, so long as you're careful about the index. (If you remove an item on a given pass through the loop, then you shouldn't increment the index on that pass.) * Collect the items to be removed by index into an NSMutableIndexSet and then use -removeObjectsAtIndexes: to remove them. * Use -filterUsingPredicate:, if it's a good match for what you're trying to do Cheers, Ken _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com