NoviceDeveloper
NoviceDeveloper

Reputation: 225

Removing two object from nsmutablearray

I have a NSMutableArray with five objects. I want to remove two objects when a certain condition is fulfilled. But it is giving me an error-----* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 3 beyond bounds [0 .. 2]' Here is my code

  -(IBAction)buttonPressed1:(id)sender{
for (int i = 0; i < [objectArray1 count]; i++) {

    if ([[objectArray1 objectAtIndex:3] isEqualToString:@"xyz"]) 
    {

        NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:3];
        [indexes addIndex:4];
        [objectArray1 removeObjectsAtIndexes:indexes];
        NSLog(@"Hello %@",objectArray1 );
  }
}

IF I remove for{} condition it is working fine. Any help will be appreciated.

Upvotes: 0

Views: 1104

Answers (2)

Mundi
Mundi

Reputation: 80271

It seems you are going through the loop 4 times.
If the condition is true, the conditional code is going to be executed 4 times.
You create an index 4.
You remove it.
The second time you remove it, you get a crash.

If I understood correctly what you want to do, this is the code:

if ([[objectArray1 objectAtIndex:3] isEqualToString:@"xyz"] && 
   objectArray1.count == 5) {
   NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:3];
   [indexes addIndex:4];
   [objectArray1 removeObjectsAtIndexes:indexes];
   //less code:
   //[objectArray1 removeLastObject];
   //[objectArray1 removeLastObject];       
}

Upvotes: 0

Tim Dean
Tim Dean

Reputation: 8292

If you want to remove the objects at indexes 3 and 4, as you seem to be doing here, then don't do it inside a loop. You are taking your array of 5 objects and removing the last 2 objects in it the first time through the loop, leaving you with 3 objects in your array. The next time through your loop you are running the same check on the item at array index 3, and the array no longer has that index because you've deleted it.

Upvotes: 4

Related Questions