2015-05-04 118 views
0

我的情況:致命錯誤:數組索引超出範圍

有一個稱爲friendCardList要求中的AppDelegate.swift陣列,並且所述CardModel只是正常類:

var friendCardList:[CardModel] = [] 

UITableViewController稱爲FriendListVC,陣列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 

enter image description here

我堵住了這裏所有的中午。

+6

提示:你從數組中刪除了數據,但是你的tableview並不知道。你需要通知你的tableview關於數據集的變化。 –

+0

@MidhunMP我正在處理類似的錯誤,你如何通知tableview的變化?我在我的代碼 – SamYoungNY

回答

7

你需要調用

self.reloadData() 
在你的UITableViewController

每次修改您的數據源。

+1

中使用了self.reloadData()非常感謝。當我添加'self.reloadData()'時,Bug就消失了。 –

+3

@EthanJoe:我不會推薦這個。重新加載整個tableview並不是一個好習慣。您可以改用deleteRowAtIndexPaths方法。查看本教程http://www.ioscreator.com/tutorials/delete-rows-from-tableview –

相關問題