【问题标题】:Fatal error: Array index out of range致命错误:数组索引超出范围
【发布时间】:2015-05-04 09:42:46
【问题描述】:

我的情况:

AppDelegate.swift 中声明了一个名为friendCardList 的数组,而CardModel 只是普通类:

var friendCardList:[CardModel] = []

在名为FriendListVCUITableViewController 中,数组friendCardList 中的元素将列在FriendListVC 中:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let card = delegate.exchangeListCards[indexPath.row]
    let cell = tableView.dequeueReusableCellWithIdentifier("CardsCell",
    forIndexPath: indexPath) as! BrowserTableViewCell
    return cell
}

我试图删除FriendListVC中的单元格:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let card = delegate.exchangeListCards[indexPath.row]
    var CardSet = NSMutableSet(array: delegate.exchangeListCards)
    CardSet.removeObject(card)
    delegate.exchangeListCards = CardSet.allObjects as! [CardModel]
} 

我的问题:

当我通过向左滑动单元格来删除单元格时,编译器抛出了错误:

fatal error: Array index out of range

我整个中午都在这儿堵着。

【问题讨论】:

  • 提示:您从数组中删除了数据,但您的 tableview 不知道这一点。您需要通知您的 tableview 有关数据集的更改。!!!
  • @MidhunMP 我正在处理类似的错误,您如何通知 tableview 更改?我在我的代码中使用了 self.reloadData()

标签: ios arrays swift


【解决方案1】:

你需要打电话

self.reloadData()

每次修改数据源时在 UITableViewController 中。

【讨论】:

  • 非常感谢。当我添加 self.reloadData( ) 时,错误消失了。
  • @EthanJoe:我不会推荐这个。重新加载整个 tableview 不是一个好习惯。您可以改用 deleteRowAtIndexPaths 方法。查看本教程ioscreator.com/tutorials/delete-rows-from-tableview
猜你喜欢
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多