斯威夫特致命错误:数组索引越界 [英] Swift fatal error: array index out of range

查看:433
本文介绍了斯威夫特致命错误:数组索引越界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个待办事项应用程序,但是当我试图从我的名单中删除的东西,X code是给我的一个错误,指出致命错误:数组索引超出范围。谁能告诉我我在做什么毛病我的数组是导致这种情况发生?

I'm making a to-do list app but when I try to delete something from my list, xcode is giving me an error that says "fatal error: array index out of range". Can someone tell me what I'm doing wrong with my array that is causing this to happen?

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 以及

推荐答案

这是不够的,从数据源数组中删除的项目。
你也必须告诉表视图,该行被删除:

It is not sufficient to remove the item from the data source array. You also have to tell the table view that the row is deleted:

if editingStyle == .Delete {

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

   // ...
}

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

Otherwise the table view will call the data source methods for the original number of rows, causing the out of range error.

另外,你可以叫 tableView.reloadData()修改数据源时,但上述方法
给出了一个更好的动画。

Alternatively, you can call tableView.reloadData() when modifying the data source, but the above method gives a nicer animation.

这篇关于斯威夫特致命错误:数组索引越界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆