I have one for
loop in my code.
When execution of this for loop continues, my application crashes and prints the following message on the console:
Terminating app due to uncaught exception 'NSRangeException', reason: '-[NSMutableArray objectAtIndex:] index 2 beyond bounds [0 .. 1]' Call stack at first throw:
Using this for
loop I am trying to fill up a NSMutableArray
but this is not what is being done.
Usually this happens when you try to access an element at an index outside of the bounds of the NSArray
.
So say you had an NSArray
like this:
NSArray *a = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
This code would print "Array index out of bounds" because bounds are 0 - 2:
@try {
NSString *string = [a objectAtIndex:3];
} @catch(NSRangeException *e) {
NSLog(@"Array index out of bounds");
}
The best way to solve this issue is to use fast enumeration:
for(id obj in array) {
//do something with obj
}
Fast enumeration uses the enumerable object's implementation of the NSFastEnumeration
protocol to handle all of the dirty work for you.
One thing that will usually cause this problem even while using fast enumeration is if you are enumerating a mutable structure such as an NSMutableArray
and inside the body of the loop, you mutate the structure by using removeObject:
or its variants, you will run into this exception sooner than later because the length of the structure is cached and therefore it will carry on to the next iteration even if it goes out of bounds.
But, using fast enumeration, you will catch this error rather quickly because the internal __NSFastEnumerationMutationHandler
will catch it and throw up the following exception:
2011-02-11 00:30:49.825 MutableNSFastEnumerationTest[10547:a0f] *** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <NSCFArray: 0x10010c960> was mutated while being enumerated.<CFArray 0x10010c960 [0x7fff70c45ee0]>{type = mutable-small, count = 2, values = (
0 : <CFString 0x100001078 [0x7fff70c45ee0]>{contents = "b"}
1 : <CFString 0x100001058 [0x7fff70c45ee0]>{contents = "c"}
)}'
*** Call stack at first throw:
(
0 CoreFoundation 0x00007fff8621e7b4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x00007fff80daa0f3 objc_exception_throw + 45
2 CoreFoundation 0x00007fff862765bf __NSFastEnumerationMutationHandler + 303
3 MutableNSFastEnumerationTest 0x0000000100000de7 main + 295
4 MutableNSFastEnumerationTest 0x0000000100000cb8 start + 52
5 ??? 0x0000000000000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With