• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: iterating and removing objects from a collection
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: iterating and removing objects from a collection


  • Subject: Re: iterating and removing objects from a collection
  • From: Ken Thomases <email@hidden>
  • Date: Mon, 30 Nov 2009 15:21:39 -0600

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 (email@hidden)

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:

This email sent to email@hidden

  • Follow-Ups:
    • Re: iterating and removing objects from a collection
      • From: Sherm Pendley <email@hidden>
References: 
 >iterating and removing objects from a collection (From: Dennis Munsie <email@hidden>)

  • Prev by Date: Re: Core Data - any way to back it with something other than SQLite 3?
  • Next by Date: Re: Keyword @defs
  • Previous by thread: iterating and removing objects from a collection
  • Next by thread: Re: iterating and removing objects from a collection
  • Index(es):
    • Date
    • Thread