0
votes

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.

2
your array doesn't contain enough objects, why are you wondering why you get a crash ? the problem is you expected 5 objects, and they are not all in the array at the time you want to remove them.user971401
my array contains five objects.NoviceDeveloper

2 Answers

4
votes

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.

0
votes

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