开发者

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.


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
}


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

[mainArray removeObjectsInArray:toRemoveObjects];


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


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;
}


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

[mainArray removeObject:objectToRemove];


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜