0

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
  • 1
    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. Commented Feb 7, 2012 at 14:06
  • my array contains five objects. Commented Feb 7, 2012 at 14:09

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Tim ,,missed the logic..:)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.