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(),但使用上述方法给出了一个更好的动画.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...