Fast fatal error: array index is out of range

I am making a to-do list application, but when I try to remove something from my list, xcode gives me the error message "fatal error: array index out of range". Can someone tell me what I'm doing wrong with my array that causes this?

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()


        }
    }
}

A breakpoint indicating that EXC_BAD_INSTRUCTION is also being created at eventList.removeAtIndex(indexPath.row).

+4
source share
2 answers

It is not enough to remove an item from an array of data sources. You should also tell the table view that the row has been deleted:

if editingStyle == .Delete {

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

   // ...
}

, .

tableView.reloadData() , .

+6

, 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()
    }
}
+1

Source: https://habr.com/ru/post/1568921/


All Articles