Re: iterating and removing objects from a collection
Re: iterating and removing objects from a collection
- Subject: Re: iterating and removing objects from a collection
- From: Jeremy Pereira <email@hidden>
- Date: Tue, 1 Dec 2009 11:49:04 +0000
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 (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
______________________________________________________________________
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 (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