Warm tip: This article is reproduced from serverfault.com, please click

arrays-子项已更新的崩溃表(indexPath超出范围错误,导致我的应用程序崩溃)

(arrays - Child Updated crashing table (indexPath is out of range error that crashes my app Error))

发布于 2020-11-25 00:38:43

我在更新用于控制表格的应用程序中的数组时遇到困难。我希望能够更改Firebase数据库中的子节点,并在用户端对其进行更新,而无需编写代码并发送更新。我需要能够更改他们的标签并使其更新表,而索引不会超出范围。

这是我的类结构,为用户提供信息:

import UIKit

class User: NSObject {
    var Name: String?
    var Email: String?
    var UID: String?
    var Tag: String?

}

在我的控制器中,我有以下代码使用Firebase中的信息初始化表:

func CreateDataArray() {
    
    Database.database().reference().child("Users").observe(.childAdded, with: { (snapshot) in
        
        if let dictionary = snapshot.value as? [String: AnyObject] {
            
            let user = User()
            //self.setValuesForKeys(dictionary)
            user.Name = dictionary["Name"] as? String
            user.Email = dictionary["Email"] as? String
            user.UID = dictionary["UID"] as? String
            user.Tag = dictionary["Tag"] as? String
            
            if user.Tag == "Macro" {
                            self.macroUsersArray.append(user)
            } else if user.Tag == "Micro" {
                            self.microUsersArray.append(user)
                        }
            
            self.users.append(user)
            self.userName.append(user.Name!)
            self.filteredNames.append(user.Name!)
            
            print(dictionary)
            print(self.macroUsersArray)
            
            DispatchQueue.main.async {
            self.tableView.reloadData()
                }
            }
        }, withCancel: nil)
    
    }

然后,我有了一个侦听Firebase的任何更改并更新数组的函数:

func updateDataArray() {
    
    Database.database().reference().child("Users").observe(.childChanged, with: { (snapshot) in
        
        if let dictionary = snapshot.value as? [String: AnyObject] {
            
            let user = User()
            //self.setValuesForKeys(dictionary)
            user.Name = dictionary["Name"] as? String
            user.Email = dictionary["Email"] as? String
            user.UID = dictionary["UID"] as? String
            user.Tag = dictionary["Tag"] as? String
            
            if user.Tag == "Macro" {
                self.microUsersArray.remove(at: 2)
            } else if user.Tag == "Micro" {
                self.macroUsersArray.remove(at: 2)
                        }
            
            self.users.append(user)
            self.userName.append(user.Name!)
            self.filteredNames.append(user.Name!)
            
            print(dictionary)
            print(self.macroUsersArray)
            
            DispatchQueue.main.async {
            self.tableView.reloadData()
                }
            }
        }, withCancel: nil)
    
    }

我想让原来具有标签“ macro”的用户切换到“ micro”,以便将其从宏列表中删除并显示在微列表中。我无法使数组追加并保持获取indexPath超出范围错误,这会使我的应用程序崩溃。我真的需要帮助,并且在过去的几周中一直在为此苦苦挣扎。

编辑:我决定使用observe.value,以便当我进行更改时将其读取。这是我用于创建用户信息的代码:

func CreateDataArray() {
    
    Database.database().reference().child("Users").observe(.value, with: { (snapshot) in
        
        if let dictionary = snapshot.value as? [String: AnyObject] {
            
            let user = User()
            //self.setValuesForKeys(dictionary)
            user.Name = dictionary["Name"] as? String
            user.Email = dictionary["Email"] as? String
            user.Tag = dictionary["Tag"] as? String
            
            if user.Tag == "Macro" {
                            self.macroUsersArray.append(user)
            } else if user.Tag == "Micro" {
                            self.microUsersArray.append(user)
                        }
            
            self.users.append(user)
            self.userName.append(user.Name!)
            self.filteredNames.append(user.Name!)
            
            print(dictionary)
            print(self.macroUsersArray)
            
            DispatchQueue.main.async {
            self.tableView.reloadData()
                }
            }
        }, withCancel: nil)
    
    }

但是,我能够将所有数据提取到快照中,但是当我尝试追加时它返回nil。我在任何带有“ append(User.Name!)

我很想弄清楚如何停止这种情况,并让观察者继续监听数据库中的更改。

编辑2:

这是我的变量:

var allUsersArray = [User]()
var macroUsersArray = [User]()
var microUsersArray = [User]()

这是我的ViewDidLoad:

 override func viewDidLoad() {
        super.viewDidLoad()
        
        updateDataArray()
        
    }

这是我的updateDataArray代码:

func updateDataArray() {
    
    Database.database().reference().child("Users").observe(.childAdded, with: { (snapshot) in
        
        if let dictionary = snapshot.value as? [String: AnyObject] {
            
            let user = User()
            //self.setValuesForKeys(dictionary)
            user.Name = dictionary["Name"] as? String
            user.Email = dictionary["Email"] as? String
            user.UID = dictionary["UID"] as? String
            user.Tag = dictionary["Tag"] as? String
            
            self.allUsersArray.append(user)
            self.users.append(user)
            self.userName.append(user.Name!)
            self.filteredNames.append(user.Name!)

            self.macroUsersArray = self.allUsersArray.filter { $0.Tag == "Macro" }
            self.microUsersArray = self.allUsersArray.filter { $0.Tag == "Micro" }
            self.observeChangeInUserProperty()
            
            DispatchQueue.main.async {
            self.tableView.reloadData()
                }
            }
        }, withCancel: nil)
    
    }

这是observeChangeInUserProperty()函数:

func observeChangeInUserProperty() {
    let ref = Database.database().reference().child("Users").child("Talent")
    ref.observe(.childChanged, with: { snapshot in
        let key = snapshot.key
        
        let tag = snapshot.childSnapshot(forPath: "Tag").value as! String // ! = never optional
        //get the user from the allUsersArray by its key
        if let user = self.allUsersArray.first(where: { $0.Tag == key }) {
            if user.Tag != tag { //if the tag changed, handle it
                user.Tag = tag //update the allUsersArray
                if tag == "Macro" { //if the new tag is Macro remove the user from the Micro array
                    if let userIndex = self.microUsersArray.firstIndex(where: { $0.Tag == key }) {
                        self.microUsersArray.remove(at: userIndex)
                        self.macroUsersArray.append(user) //add user to macro array
                    }
                } else { //new type is micro so remove from macro array
                    if let userIndex = self.macroUsersArray.firstIndex(where: { $0.Tag == key }) {
                        self.macroUsersArray.remove(at: userIndex)
                        self.microUsersArray.append(user)
                    }
                }
                //reload the tableviews to reflect the changes
                self.microTableView.reloadData()
                self.tableView.reloadData()
                
            }
        }
    })
}

我正在为宏观和微观的空数组。我不知道我在做什么错。

编辑3:

这是从Firebase初始化的新用户结构:

import UIKit
import Firebase

class User: NSObject {
    var Name: String?
    var Email: String?
    var UID: String?
    var Tag: String?

    init?(from snapshot: DataSnapshot) {

        let dictionary = snapshot.value as? [String: Any]
    
            self.Name = dictionary!["Name"] as? String
            self.Email = dictionary!["Email"] as? String
            self.UID = dictionary!["UID"] as? String
            self.Tag = dictionary!["Tag"] as? String

        }
    }

现在,我可以追加数组,但它们不会填充我的表。我还可以在Firebase中更改用户的标签,而不会导致应用程序崩溃,但是它不会观察到更改后的标签并将用户移至其他阵列。因此,在这两件事上我需要帮助。

Questioner
NewCoder
Viewed
0
Jay 2020-12-04 03:46:05

这个答案将需要一些设置和重述目标

目标是拥有两个数组,用作两个tableViews的数据源。一个数组包含用户类型:宏,另一个数组包含用户类型:微型。

如果将用户类型从宏更改为微型(反之亦然),则OP希望从一个表中删除该用户并将其添加到另一个表中。

从概念上讲,答案是:将观察者添加到Firebase中的users节点,并且当用户发生更改时,查看它是否是type属性,如果是,则从一个表中删除并将其添加到另一个表中。

有很多解决方案,但让我提出这个冗长的答案,可以通过代码和属性观察者来减少。

从三个数组开始,一个数组容纳所有用户,另一个数组容纳宏观和微观用户。假设UserClass的Stringtype属性为macromicro

var allUsersArray = [UserClass]()
var macroArray = [UserClass]()
var microArray = [UserClass]()

读入所有用户,然后从中将用户划分为各自的类型

...read firebase single event of .value, with: { snapshot in
   and populate allUsersArray from the snapshot..
   self.macroArray = self.allUsersArray.filter { $0.type == "macro" }
   self.microArray = self.allUsersArray.filter { $0.type == "micro" }
   self.observeChangeInUserProperty()
}

下面的代码将观察者添加到users数组,当用户的任何属性更改时,该观察者将通知应用程序,并在快照中显示该用户节点。

func observeChangeInUserProperty() {
    let ref = self.ref.child("users")
    ref.observe(.childChanged, with: { snapshot in
        let key = snapshot.key
        let type = snapshot.childSnapshot(forPath: "type").value as! String // ! = never optional
        //get the user from the allUsersArray by its key
        if let user = self.allUsersArray.first(where: { $0.key == key }) {
            if user.type != type { //if the type changed, handle it
                user.type = type //update the allUsersArray
                if type == "macro" { //if the new type is macro remove the user from the micro array
                    if let userIndex = self.microArray.firstIndex(where: { $0.key == key }) {
                        self.microArray.remove(at: userIndex)
                        self.macroArray.append(user) //add user to macro array
                    }
                } else { //new type is micro so remove from macro array
                    if let userIndex = self.macroArray.firstIndex(where: { $0.key == key }) {
                        self.macroArray.remove(at: userIndex)
                        self.microArray.append(user)
                    }
                }
                //reload the tableviews to reflect the changes
                self.microTable.reloadData()
                self.mactoTable.reloadData()
            }
        }
    })
}

如前所述,这是很多无关的代码,可以与属性观察器压缩在一起,或者为两个表或许多其他解决方案利用单个数组。

编辑

如果你想知道如何从Firebase填充所有用户数组,则需要有一个从快照初始化的User类,这是代码

func loadAllUsersAndPopulateArray() {
    let ref = self.ref.child("users")
    ref.observeSingleEvent(of: .value, with: { snapshot in
        let allUsersSnapshot = snapshot.children.allObjects as! [DataSnapshot]
        for userSnap in allUsersSnapshot {
            let user = UserClass(withSnap: userSnap)
            self.allUsersArray.append(user)
        }
    })
}