在iOS上“由于未捕获的exception而终止应用程序”

我有一个for循环在我的代码。 当继续执行for循环时,我的应用程序崩溃并在控制台上输出以下消息:

 Terminating app due to uncaught exception 'NSRangeException', reason: '-[NSMutableArray objectAtIndex:] index 2 beyond bounds [0 .. 1]' Call stack at first throw: 

使用这个for循环,我想填充一个NSMutableArray但这不是正在做什么。

通常情况下,当您尝试访问NSArray边界之外的索引处的元素时,会发生这种情况。

所以说你有这样一个NSArray

 NSArray *a = [NSArray arrayWithObjects:@"a", @"b", @"c", nil]; 

此代码将打印“数组索引越界”,因为边界是0 – 2:

 @try { NSString *string = [a objectAtIndex:3]; } @catch(NSRangeException *e) { NSLog(@"Array index out of bounds"); } 

解决这个问题的最好方法是使用快速枚举

 for(id obj in array) { //do something with obj } 

快速枚举使用NSFastEnumeration协议的可枚举对象的实现来处理所有肮脏的工作。

有一件事通常会导致这个问题,甚至在使用快速枚举的时候,如果你正在枚举一个可变结构,例如NSMutableArray并且在循环体内部,你可以使用removeObject:或者其变体来改变结构,因为结构的长度被caching,所以即使超出界限,它也会继续下一次迭代。

但是,使用快速枚举,你会很快赶上这个错误,因为内部的__NSFastEnumerationMutationHandler会抓住它并引发下面的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' 

exception的types称为索引超出限制的exception。当您尝试访问不存在的数组元素时,通常会发生这种情况。

你的exception意味着你试图访问数组中超出范围的东西(索引2超出范围)。 如果你只需访问数组,最好的办法就是使用快速枚举(每个循环)。

 for (NSString *str in array) NSLog(@"%@", str); 

像这样的东西可以防止任何索引越界exception。