通常,当您尝试访问索引超出范围的元素时,就会发生这种情况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:
或其变体,您迟早会遇到此异常,因为结构的长度被缓存,因此即使它超出范围,它也会继续到下一次迭代。
但是,使用快速枚举,您将很快捕获此错误,因为内部__NSFastEnumerationMutationHandler
将捕获它并抛出以下异常:
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'