是否有一种常见的方法来避免崩溃 - [__ NSCFArray objectAtIndex:]:index(i)超出界限

时间:2015-06-03 14:18:10

标签: ios iphone

我希望帮助其他人修复项目的错误

我注意到所有错误的1/2以上都是

- [__ NSCFArray objectAtIndex:]:index(i)超出界限

NSRangeException(SIGABRT)

-[__NSCFArray objectAtIndex:]: index (3) beyond bounds (3)
0   CoreFoundation  0x00000001822682d8  ___exceptionPreprocess
1   libobjc.A.dylib     0x0000000193a940e4  objc_exception_throw + 56
2   CoreFoundation  0x0000000182268218  -[NSException initWithCoder:]
3   CoreFoundation  0x0000000182165a9c  -[__NSCFArray objectAtIndex:]
4   SoYoungMobile40     0x00000001000bae98  0x0000000100030000 + 568976
5   SoYoungMobile40     0x00000001001609c0  0x0000000100030000 + 1247680
6   UIKit   0x0000000186d0c77c  -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:]
7   UIKit   0x0000000186d0a754  -[UICollectionView _updateVisibleCellsNow:]
8   UIKit   0x0000000186d06004  -[UICollectionView layoutSubviews]
9   UIKit   0x0000000186ca5760  -[UIView(CALayerDelegate) layoutSublayersOfLayer:]
10  QuartzCore  0x00000001865ede1c  -[CALayer layoutSublayers]
11  QuartzCore  0x00000001865e8884  CA::Layer::layout_if_needed(CA::Transaction*)
12  QuartzCore  0x00000001865e8728  CA::Layer::layout_and_display_if_needed(CA::Transaction*)
13  QuartzCore  0x00000001865e7ebc  CA::Context::commit_transaction(CA::Transaction*)
14  QuartzCore  0x00000001865e7c3c  CA::Transaction::commit()
15  QuartzCore  0x000000018663e1f4  CA::Display::DisplayLink::dispatch_items(unsigned long long, unsigned long long, unsigned long long)
16  IOKit   0x0000000183419470  IODispatchCalloutFromCFMessage + 376
17  CoreFoundation  0x000000018220adc4  ___CFMachPortPerform
18  CoreFoundation  0x000000018221fa54  ___CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
19  CoreFoundation  0x000000018221f9b4  ___CFRunLoopDoSource1
20  CoreFoundation  0x000000018221d934  ___CFRunLoopRun
21  CoreFoundation  0x00000001821492d4  CFRunLoopRunSpecific + 392
22  GraphicsServices    0x000000018b95f6fc  GSEventRunModal + 156
23  UIKit   0x0000000186d0efac  UIApplicationMain + 1476
24  SoYoungMobile40     0x0000000100445590  0x0000000100030000 + 4281744
25  libdyld.dylib   0x0000000194112a08  _start

从用户发回的信息中,我找不到确切的崩溃位置。

是否存在避免索引超出边界错误的常用方法。

我的方法是在objectAtIndex之前添加一些代码,但我不知道这是否正常。

您的评论欢迎

2 个答案:

答案 0 :(得分:3)

可以 执行其他人提出的建议,例如在使用之前将索引包装在if语句中,但 I在您描述 的情况下,我们不会推荐它。

虽然您可以调试它,但您应该这样做。在异常的堆栈跟踪之后,找到使用无效数组索引的代码并修复它。这是一个错误和防止崩溃的方法"是修理它,而不是掩盖它,恕我直言。

答案 1 :(得分:1)

if (index >= 0 && index < array.count) {
    id object = array[index];
} else {
    #ifdef DEBUG
        // catch any bugs in development
        [NSException raise:@"Index out of bounds." format:@"Index (%@) is out of bounds of array (%@)", index, array.count];
    #else
        NSLog(@"Index out of bounds.");  // log in release
    #endif
}