On 30 Nov 2009, at 21:21, Ken Thomases wrote:

> 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

Another alternative

NSMutableArray* newArray = [[NSMutableArray alloc] init];
for (NSObject* foo in myArray)
{
        if (!needToRemoveFoo)
        {
                [newArray addObject: foo];
        }
}
[self setMyArray: newArray];

Might be better if the assumption that adding objects to the end of an array is 
faster than removing them from the middle holds and the app can take the memory 
overhead of two possibly identical arrays for a brief period of time. 


> 
> 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/adc%40jeremyp.net
> 
> This email sent to a...@jeremyp.net


______________________________________________________________________
This email has been scanned by the MessageLabs Email Security System.
For more information please visit http://www.messagelabs.com/email 
______________________________________________________________________
_______________________________________________

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

Reply via email to