This usually happens when you try to access an element with an index outside the borders of NSArray .
So say you had NSArray :
NSArray *a = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
This code will print “Array Index Outside of Borders” because the borders are 0 - 2:
@try { NSString *string = [a objectAtIndex:3]; } @catch(NSRangeException *e) { NSLog(@"Array index out of bounds"); }
The best way to solve this problem is to use a quick enumeration :
for(id obj in array) {
Fast enumeration uses an enumerated implementation of the NSFastEnumeration protocol NSFastEnumeration to handle all the dirty work for you.
One thing that usually causes this problem, even when using fast enumeration, is if you enumerate a mutable structure such as NSMutableArray and inside the loop body, you mutate the structure using removeObject: or its variants, you will encounter this exception earlier than later, because the length of the structure is cached, and therefore it will continue until the next iteration, even if it goes beyond.
But using a quick enumeration, you will catch this error pretty quickly, because the internal __NSFastEnumerationMutationHandler will catch it and throw 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'
source share