[英]Swift fatal error: array index out of range
我正在制作一个待办事项列表应用程序但是当我尝试从列表中删除某些内容时,xcode会给出一个错误,上面写着“致命错误:数组索引超出范围”。 有人能告诉我,我的阵列出错了导致这种情况发生吗?
import UIKit
class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
cell.textLabel?.text = eventList[indexPath.row]
return cell
}
override func viewWillAppear(animated: Bool) {
if var storedEventList : AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("EventList") {
eventList = []
for var i = 0; i < storedEventList.count; ++i {
eventList.append(storedEventList[i] as NSString)
}
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if(editingStyle == UITableViewCellEditingStyle.Delete) {
eventList.removeAtIndex(indexPath.row)
NSUserDefaults.standardUserDefaults().setObject(eventList, forKey: "EventList")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
}
断点表示正在eventList.removeAtIndex(indexPath.row)
创建eventList.removeAtIndex(indexPath.row)
。
仅从数据源数组中删除该项是不够的。 您还必须告诉表视图该行已删除:
if editingStyle == .Delete {
eventList.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
// ...
}
否则,表视图将调用原始行数的数据源方法,从而导致超出范围错误。
或者,您可以在修改数据源时调用tableView.reloadData()
,但上面的方法可以提供更好的动画。
这意味着你试图访问一个索引, indexPath.row
,超出eventList
范围。 要解决此问题,请尝试:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if(editingStyle == .Delete && indexPath.row < eventList.count) {
eventList.removeAtIndex(indexPath.row)
tableView.reloadData()
NSUserDefaults.standardUserDefaults().setObject(eventList, forKey: "EventList")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.