Oliver
Oliver

Reputation: 23540

Cocoa - Delete/remove items while parsing a NSMutableArray

I'd like to parse a NSMutableArray, and when I find some objects that respond to some conditions, I'd like to remove them from the array.

How may I do this without having two (or more) array for the process ?

For those who will be tempted to say : Hey, it's just impossible to parse AND remove objects from an array, I just can say that when I parse a drawer from which I want to remove out of date medicines, I do not have problem to do it... When I find one, I trash it, then I look for the next medicine box to check. I do not need a second drawer.

Upvotes: 1

Views: 959

Answers (6)

Oliver
Oliver

Reputation: 23540

I found a super elegant solution, that works with 2 arrays, ok, but that prevents to make a parsing loop in many situations ;

NSArray* matchingItems = [mainArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@" attributetockeck MATCHES[cd] %@ ", attributevalue]];
[mainArray removeObjectsInArray:matchingItems];

Upvotes: 0

paulmelnikow
paulmelnikow

Reputation: 17218

If you're validating the objects one at a time, you can use this instead:

[mainArray removeObject:objectToRemove];

Upvotes: 0

Khomsan
Khomsan

Reputation: 553

I use backward loop when I need to remove object from mutable array.

for (NSInteger i = arrayCount - 1; i >= 0; i--) {
    // remove is OK here
}

Upvotes: 6

Nathan Day
Nathan Day

Reputation: 6037

for( NSUInter i = 0, j = 0; i < array.count; i++ )
{
    if( test )
        [array removeObjectAtIndex:j];
    else
        j++;
}

Here is the code in a command line version you can run and test yourself it removes every odd number

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    NSAutoreleasePool       * pool = [[NSAutoreleasePool alloc] init];
    NSMutableArray          * array = [NSMutableArray array];

    for( NSUInteger i = 0; i < 20; i++ )
        [array addObject:[NSNumber numberWithInteger:random()%100]];


    NSLog( @"%@", array );

    for( NSUInteger i = 0, j = 0; i < array.count; i++ )
    {
        if( [[array objectAtIndex:j] unsignedIntegerValue] & 1 )
            [array removeObjectAtIndex:j];
        else
            j++;
    }   

    NSLog( @"%@", array );

    [pool drain];
    return 0;
}

Upvotes: 0

dasdom
dasdom

Reputation: 14073

I would copy the objects you want to keep into a new mutable array and assign the old array afterwards to the new array.

Upvotes: 1

Srikar Appalaraju
Srikar Appalaraju

Reputation: 73658

If you have 2 Arrays. Both of type NSMUtableArray. you can simply do -

[mainArray removeObjectsInArray:toRemoveObjects];

Upvotes: 2

Related Questions