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()
}
}
}
A breakpoint saying EXC_BAD_INSTRUCTION is being created at the eventList.removeAtIndex(indexPath.row)
as well.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…