user2032083
user2032083

Reputation: 313

how to remove objects from NSMutableArray correctly?

I try to delete items from NSMutableArray in loop. I have an array :(2,3,4,5,6).

       int j = [array count];        
       while (array != NULL) {

         NSUInteger g = 0;
    for (int q = 0; q < j; q++) {

        [array removeObjectAtIndex:g];
        }

When i set a breakpoint (after first iteration) i got the following:

[0]=(id)0x00000000
[1]=(id)0x071421a0(int)3
[2]=(id)0x071421b0(int)4
[3]=(id)0x071421e0(int)5

I don't understand how to delete in each iteration a first object. I mean that following it will be first. And why the last one is disappeared every time also? Thanks.

Upvotes: 1

Views: 872

Answers (4)

Javier Cancio
Javier Cancio

Reputation: 1438

You CAN'T remove objects from NSMutableArray inside a loop. This is because, in that case, array size is changing over each iteration (worst case) and you could try to access to an out of bounds index.

The best option is Jeremy's solution. Keep desired objects on separated array and then remove these objects from the main array, outside of the loop.

Upvotes: 1

Jeremy
Jeremy

Reputation: 9010

Another way to delete a collection of objects from an array is to add the objects you want to delete to a separate array, then use that to delete your objects from the primary array in one fell swoop. There are benefits to this, least of which would be no risk of out-of-bounds, and also the possibility for rolling back since you are essentially removing in a single batch process:

int j = [array count];  
NSMutableArray *theseObjects = [NSMutableArray array];
for (int q = 0; q < j; q++)
{
    id thisObject = [array objectAtIndex:q];
    BOOL shouldRemoveThisObject = ...//<--determine if you want to remove this object
    if (shouldRemoveThisObject)
        [theseObjects addObject:thisObject];
}
[array removeObjectsInArray:theseObjects];

Upvotes: 3

Anoop Vaidya
Anoop Vaidya

Reputation: 46533

You cant do as you are trying to do.

j is set to 5 (array count) but the array's size is reducing on every iteration. So at one point of time it will try to access array out-of-bound, hence exception and your app will crash.

Instead you need to do as below:

while (array.count > 0) {
    NSLog(@"Arr before removal is  : %@",array);
    [array removeObjectAtIndex:0];
    NSLog(@"Arr after removal is  : %@",array);

}

If for some other reason you want to remove only first then the above will work.

If you want to remove all the objects at one go: you can use:

[array removeAllObjects];

Upvotes: 1

dehlen
dehlen

Reputation: 7389

It looks like you want to remove all entries. Then you could also call [myArray removeAllObjects];

Upvotes: 1

Related Questions