在rangeexception索引边界上崩溃

时间:2018-09-18 08:29:32

标签: ios swift xcode

我使用OperationQueue在后台运行了一些进程,该进程崩溃了,错误为“'NSRangeException',原因:'* -[__ NSArrayM objectAtIndex:]:索引2超出范围[0。 。1]' “ **在应用程序委托中,我没有弄明白错误在哪里

  

在此行它崩溃了

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

1 个答案:

答案 0 :(得分:0)

您正在尝试从甚至不存在的 booklist array的索引中获取对象。例外情况是,您尝试从索引2获取对象,但数组中只有2个对象。请尝试在从数组获取对象之前进行检查,如下所示:

func objectAtIndex(index : Int) -> Any? { 
    if index < booklist.count {
        return booklist?[index] 
    } else {
        //The index does not exist in the array.
    }
}