2016-06-26 61 views
0

我有一個函數,用於偵聽添加到Firebase數據庫的新對象,將這些新對象附加到數組,然後使用該數組填充tableView。我無法弄清楚如何從數組中刪除一個對象。我認爲我在正確的軌道上,但我不知道如何「撤銷」一個附加。如何從陣列中刪除Firebase快照?

這是我到目前爲止有:

func configureDatabase() { 

    // Listen for new messages in the Firebase database 
    let ref = self.rootRef.child("invites").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in 

    self.invites.append(snapshot) 
    self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.invites.count-1, inSection: 0)], withRowAnimation: .Automatic) 
    }) 

    //listen for deleted messages in Firebase database 
    let ref2 = self.rootRef.child("invites").observeEventType(.ChildRemoved, withBlock: { (snapshot) -> Void in 

    //remove from invites array and refresh table?? 
    }) 
} 

我必須從表中的實際單元格傳遞價值?

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("AlertCell", forIndexPath: indexPath) as! AlertCell 

     //get user, set cell text 
     let inviteDict = invites[indexPath.row].value as! [String : AnyObject] 
} 

回答

3

我找到了火力地堡網站上的代碼示例答案:

// Listen for deleted comments in the Firebase database 
    commentsRef.observeEventType(.ChildRemoved, withBlock: { (snapshot) -> Void in 
     let index = self.indexOfMessage(snapshot) 
     self.comments.removeAtIndex(index) 
     self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 1)], withRowAnimation: UITableViewRowAnimation.Automatic) 
    }) 

func indexOfMessage(snapshot: FIRDataSnapshot) -> Int { 
    var index = 0 
    for comment in self.comments { 
     if (snapshot.key == comment.key) { 
     return index 
     } 
     index += 1 
    } 
    return -1 
    }