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.
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.