由于未捕获的异常 'NSRangeException' 而终止应用程序,原因:'*** -[__NSArray0 objectAtIndex:]:索引 2 超出空 NSArray 的范围

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 2 beyond bounds for empty NSArray

日志错误:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSArray0 objectAtIndex:]: index 2 beyond bounds for empty NSArray' *** First throw call stack: ( 0 CoreFoundation 0x000000010fdd8b0b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x00000001143a6141 objc_exception_throw + 48 2 CoreFoundation 0x000000010fdf027d -[__NSArray0 objectAtIndex:] + 93 3 DropInn 0x000000010d598fc4 _TFC7DropInn21ListingViewController9tableViewfTCSo11UITableView14didSelectRowAtV10Foundation9IndexPath_T_ + 5972 4 DropInn 0x000000010d599837 _TToFC7DropInn21ListingViewController9tableViewfTCSo11UITableView14didSelectRowAtV10Foundation9IndexPath_T_ + 87 5 UIKit 0x00000001122b3dcd -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1763 6 UIKit 0x00000001122b3fe3 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 344 7 UIKit 0x00000001121697f3 _runAfterCACommitDeferredBlocks + 318 8 UIKit 0x00000001121567bc _cleanUpAfterCAFlushAndRunDeferredBlocks + 532 9 UIKit 0x000000011218828c _afterCACommitHandler + 137 10 CoreFoundation 0x000000010fd7e717 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23 11 CoreFoundation 0x000000010fd7e687 __CFRunLoopDoObservers + 391 12 CoreFoundation 0x000000010fd63720 __CFRunLoopRun + 1200 13 CoreFoundation 0x000000010fd63016 CFRunLoopRunSpecific + 406 14 GraphicsServices 0x0000000118249a24 GSEventRunModal + 62 15 UIKit 0x000000011215d0d4 UIApplicationMain + 159 16 DropInn 0x000000010d240f47 main + 55 17 libdyld.dylib 0x0000000115fba65d start + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException

错误截图:

源代码:

let savearr : NSArray = (UserDefaults.standard.object(forKey: "savedarray") as! NSArray)

print("Savearr data ->", savearr)

let addarr: NSArray = savearr.value(forKeyPath:"country") as! NSArray
let sumarr: NSArray = savearr.value(forKeyPath:"description") as! NSArray
let titarr: NSArray = savearr.value(forKeyPath:"title") as! NSArray

appDelegate.indexrow = indexPath.row

print("addarr\(addarr)")
print("sumarr\(sumarr)")
print("titarr\(titarr)")

let MenuViewController = self.storyboard?.instantiateViewController(withIdentifier: "five") as! FiveStepsViewController

MenuViewController.writeTitleString = String(describing: titarr[indexPath.row])

MenuViewController.writeSummaryString = String(describing: sumarr[indexPath.row])

MenuViewController.writeAddressString = String(describing: addarr[indexPath.row])

//MenuViewController.writePriceString = String(describing: self.appDelegate.fivepricearray[indexPath.row])

self.present(MenuViewController, animated: true, completion: nil)

错误显示在:

MenuViewController.writeTitleString = String(describing: titarr[indexPath.row])

MenuViewController.writeSummaryString = String(describing: sumarr[indexPath.row])

MenuViewController.writeAddressString = String(describing: addarr[indexPath.row])
if ( titarr.count > 0 ) {
   // rest of your code
}

Apple's document 说过:

NSRangeException

Name of an exception that occurs when attempting to access outside the bounds of some data, such as beyond the end of a string.

根据您的具体情况,三个数组之一(或可能全部)titarrsumarraddarr 是空数组,您正在尝试访问空数组的索引 => NSRangeException

要解决这个问题,您可以:

检查数组是否非空:

if !titarr.isEmpty {
    // titarr is non-empty
}

或者,为了更安全,检查你要访问的索引是否不超过数组的数据限制:

if titarr.count > yourIndex {
    // index is valid
}

但是,我更喜欢直接访问索引,如果超出范围,它将return nil。为此,请参阅 @kkuushkin's answer in the question.

例如,像这样:

let titarr = [1, 2, 3]

// Access the index beyond bounds, value is nil, no NSRangeException
titarr[safe: 5]