简体   繁体   English

Firebase + Swift:无法删除tableView中的行

[英]Firebase + Swift: Unable to delete rows in tableView

I am fairly new to the realm of coding and I am trying to implementing tableView with Firebase. 我是编码领域的新手,我正在尝试使用Firebase实现tableView。 What I am trying to achieve is to: 我想要达到的目标是:

  1. Create a 'settings' page using tableView where users can input their favourite location 使用tableView创建一个“设置”页面,用户可以在其中输入自己喜欢的位置
  2. Create a form (I use Eureka here) for users to pick certain options from the favourites they input in the settings page 创建一个表单(我在这里使用Eureka)供用户从他们在设置页面中输入的收藏夹中选择某些选项
  3. Allow deletion of those 'favourites' 允许删除那些“收藏夹”

In order for the forms to work, I pull the Firebase data at AppDelegate filtered by user.uid. 为了使表单正常工作,我将AppDelegate上的Firebase数据拉到了user.uid过滤的位置。 to populate those 'favourites settings'. 填充这些“收藏夹设置”。 When I try to delete rows using commitEdittingStyle at the 'settings' , it throws the error of invalid number of rows. 当我尝试在'settings'处使用commitEdittingStyle删除行时,它将引发错误的行数错误。 I tried googling various solution and also attempted dispatch_async but it somehow just doesn't quite solve my problem. 我尝试使用Google搜索各种解决方案,还尝试了dispatch_async,但它并不能完全解决我的问题。 Some snippets of my code as follows: 我的代码片段如下:

public var setUpFavLocations: [(String)] = []
public var favLocDatabase: [FIRDataSnapshot]! = []


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var ref: FIRDatabaseReference!
var _refHandle: FIRDatabaseHandle!

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    FIRApp.configure()

    let favLocVC: UITableViewController = FavLocationsTableViewController(style: UITableViewStyle.Plain)


    ref = FIRDatabase.database().reference()

    if let user = FIRAuth.auth()?.currentUser {

        self.ref.child("settings").queryOrderedByChild("user").queryEqualToValue(user.uid).observeEventType(.ChildAdded, withBlock: { (snapshot) in
            favLocDatabase.append(snapshot)
            let insertionIndexPath = NSIndexPath(forRow: favLocDatabase.count - 1, inSection: 0)
            favLocVC.tableView.insertRowsAtIndexPaths([insertionIndexPath], withRowAnimation: .Automatic)
        })

        self.ref.child("settings").queryOrderedByChild("user").queryEqualToValue(user.uid).observeEventType(.ChildAdded, withBlock: { (snapshot) in
            setUpFavLocations.append(snapshot.value?["favLocation"] as! String)
        })

//At FavLocationsTableViewController, aka at the settings page
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("count \(setUpFavLocations.count)")
    return setUpFavLocations.count
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    if editingStyle == .Delete {

        if let user = FIRAuth.auth()?.currentUser {
            let row = favLocDatabase[indexPath.row]

            self.ref.child("settings").queryOrderedByChild("user").queryEqualToValue(user.uid).observeEventType(.ChildRemoved, withBlock: { (snapshot) -> Void in
                   favLocDatabase.removeAtIndex(indexPath.row)
                   self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: indexPath.row, inSection: 0)], withRowAnimation: .Automatic)

            })
            row.ref.removeValue()
        }

    }
}

Doing this throws me the following error 这样做会引发以下错误

Terminating app due to uncaught exception 由于未捕获的异常而终止应用程序
'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (5), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).' 'NSInternalInconsistencyException',原因:'无效更新:第0节中的行数无效。更新(5)之后现有节中包含的行数必须等于更新前该节中包含的行数(5 ),加上或减去从该部分插入或删除的行数(已插入0,已删除1),加上或减去移入或移出该部分的行数(0移入,0移出)。

Pls help, I'm pretty stuck here for days. 请帮助,我在这里呆了好几天。 Much appreciated. 非常感激。

You are creating a new listener every time you delete a row, that can't be good. 每次删除行时,您都在创建一个新的侦听器,这不好。

Try moving: 尝试移动:

self.ref.child("settings").queryOrderedByChild("user").queryEqualToValue(user.uid).observeEventType(.ChildRemoved, withBlock: { (snapshot) -> Void in
    favLocDatabase.removeAtIndex(indexPath.row)
    self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: indexPath.row, inSection: 0)], withRowAnimation: .Automatic)
})

into your AppDelegate with the other listeners. 与其他侦听器一起进入您的AppDelegate。

Also I noticed you are not handling your observers, so when you open and close your app, the observers will duplicate. 另外我还注意到您没有处理观察者,因此,当您打开和关闭应用程序时,观察者将重复。 You should remove the observers when the app enters the background and re-instantiate them when the app enters the foreground. 当应用程序进入背景时,应删除观察者;当应用程序进入前景时,应重新实例化它们。 You'll find methods for these events in your AppDelegate. 您将在AppDelegate中找到这些事件的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM