我在 firebase 的节点中添加或删除数据时发生错误。在 firebase 上添加或删除数据时,出现数组索引越界错误。我的数组有两个项目,但 tableView 认为有三个项目,因此试图访问一个不存在的值。我不知道如何防止这种情况。对于更多上下文,我正在使用带有闭包的 alertView,该闭包在 firebase 中执行信息的添加或删除。这个 alertView 在 didSelectCellAtIndexPath 方法中。像这样访问数组时,错误发生在 cellForRowAtIndexPath 方法中 user.id = self.bookRequestors[indexPath.row]
这是我写的一些代码: `
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
}
编辑 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()
})
}
}
最佳答案
如果没有看到您的代码,很难说出到底发生了什么,但这是我最好的猜测:
您正在使用 self.bookRequestors
支持您的单元格,您说这是由前一个 VC 分配的静态数组。
但是您正在使用 userInfoArray.count
来支持 tableView 中的行数,并且此值会在您的 usersRef.observe
方法中发生变化。
具体来说,您要附加到 userInfoArray
;所以 userInfoArray.count
严格增加。
因此,如果两个数组 statrt 的大小相同,并且确定计数的数组越来越大,但您要索引的数组的大小始终相同,那么最终您将索引越界。
根据单元格中实际显示的数据返回行数。
关于ios - 从 Firebase 更新或删除数据时数组索引出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48980377/