我在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()
})
}
}