ios – Swift致命错误:数组索引超出范围

我正在制作一个待办事项列表应用程序,但是当我尝试从列表中删除某些内容时,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)中创建EXC_BAD_INSTRUCTION.

解决方法

仅从数据源数组中删除该项是不够的.
您还必须告诉表视图该行已删除:
if editingStyle == .Delete {

    eventList.removeAtIndex(indexPath.row)
    tableView.deleteRowsAtIndexPaths([indexPath],withRowAnimation: .Automatic)

   // ...
}

否则,表视图将调用原始数据源方法
行数,导致超出范围错误.

或者,您可以在修改数据源时调用tableView.reloadData(),但使用上述方法给出了一个更好的动画.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...