【问题标题】:Array index Error when updating or removing data from Firebase从 Firebase 更新或删除数据时出现数组索引错误
【发布时间】:2018-02-26 01:48:57
【问题描述】:

我在 firebase 中的节点添加或删除数据时出现错误。在 firebase 上添加或删除数据时,出现数组索引越界错误。我的数组有两个项目,但 tableView 认为有三个项目,因此尝试访问一个不存在的值。我不知道如何防止这种情况。有关更多上下文,我正在使用带有闭包的 alertView,该闭包执行在 firebase 中添加或删除信息。此 alertView 在 didSelectCellAtIndexPath 方法中。像这样user.id = self.bookRequestors[indexPath.row]

访问数组时,cellForRowAtIndexPath 方法中发生错误

这是我写的一些代码: `

   alertVC.addAction(PMAlertAction(title: "Approve this users request",            
     style: .default, action: {
        print("Book Approved")
        let user = User()

        user.id = self.bookRequestors[indexPath.row]

        var users = self.userInfoArray[indexPath.row]

        var bookRef = Database.database().reference().child("books").child("-" + self.bookID)

        bookRef.observeSingleEvent(of: .value, with: { (snapshot) in
            var tempDict = snapshot.value as! [String:AnyObject]



            if tempDict["RequestApproved"] == nil || tempDict["RequestApproved"] as! String == "false"{

                //bookRef.updateChildValues(["RequestApproved": "true", "ApprovedRequestor": user.id])
                bookRef.updateChildValues(["RequestApproved": "true", "ApprovedRequestor": user.id], withCompletionBlock: { (error, ref) in

                    let userRef = Database.database().reference().child("users").child(user.id!).child("requestedBooks")
                    // true meaning this book has been approved for this user
                    userRef.updateChildValues(["-" + self.bookID:"true"])
                })

            } else{

                print("Already Approved!")

                 let alertVC = PMAlertController(title: "Sorry?", description: "You Already Approved that book for someone Else", image: UIImage(named: "booksandcoffee.jpg"), style: .alert)

                alertVC.addAction(PMAlertAction(title: "Ok", style: .default))

                self.present(alertVC, animated: true, completion: nil)

            }

        })`

编辑:更多上下文代码

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "people", for: indexPath) as! RequestTableViewCell

    // Configure the cell...

 var users = self.userInfoArray[indexPath.row]


    var myName = users["name"]
    var myPic = users["profileImageUrl"]


    let user = User()
    print("This is a count: \(self.bookRequestors.count)")

    print ("the index is: \(indexPath)")

  //This is the array throwing the error, but this array is populated from the previous view and is not modified afterwards.
    user.id = self.bookRequestors[indexPath.row]





    cell.userImage?.setRounded()
    cell.userImage.clipsToBounds = true






    let processor = RoundCornerImageProcessor(cornerRadius: 100)

    DispatchQueue.main.async {

        cell.userImage.loadImageUsingCacheWithUrlString(myPic as! String)

    }


    cell.userName.text = myName as! String

        if user.id == approvedRequestorID{
            cell.wasApproved.image = UIImage(named: "icons8-checked_filled.png")
            cell.approvedLabel.text = "You approved to swap with: "
        }


    cell.backgroundColor = .clear

    return cell
}

EDIT II:这是我的 numberofSections 和 numberofRowsPerSection 方法

 override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return userInfoArray.count
}

编辑 III:更新 userInfoArray 的函数。

 func grabUsers(){
    //print(bookRequestors)
    for requests in bookRequestors{

    let usersRef = Database.database().reference().child("users").child(requests)

        usersRef.observe(.value, with: { (snapshot) in

            var myDict:[String: AnyObject] = [:]

            myDict = snapshot.value as! [String:AnyObject]

            self.userInfoArray.append(myDict)

            self.tableView.reloadData()
        })

    }

}

【问题讨论】:

  • 您可能希望将数据树显示为图片。
  • @ElTomato ,数据正在firebase中正确添加和删除。当我重新启动应用程序时,数据被正确读取并且没有崩溃。该问题仅在添加或删除值时出现在客户端。
  • "该问题仅在客户端添加或删除值时出现。"原因非常明显。但是您没有显示所有相关的代码行。
  • 当数组本身没有被修改时,我不明白在 firebase 中添加或删除数据是如何导致问题的。数组中的数据也没有被修改。但是一个额外的单元格是如何添加的,不确定如何添加。当我打印出单元格 indexPath 时,它会在加载表格时返回 [0,0], [0,1] 。在我对 firebase 数据库执行更改后,indexPath 返回 [0,0]、[0,1]、[0,2]。同样,我没有修改数组或引发错误的数组中包含的数据。
  • 你需要展示你的numberOfSections和numberOfRowsInSection方法。

标签: ios swift uitableview firebase


【解决方案1】:

如果没有看到您的代码,很难判断到底发生了什么,但这是我的最佳猜测:

您正在使用 self.bookRequestors 支持您的单元格,您说这是由前一个 VC 分配的静态数组。

但是,您使用 userInfoArray.count 来支持 tableView 中的行数,并且此值会在您的 usersRef.observe 方法中发生变化。

具体来说,您要附加到userInfoArray;所以userInfoArray.count严格增加。

因此,如果两个数组 statrt 的大小相同,并且确定计数的数组越来越大,但您要索引的数组始终大小相同,那么最终您将索引超出范围。

按您在单元格中实际显示的数据返回行数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2015-12-28
    • 2020-08-25
    相关资源
    最近更新 更多