为什么我的数组 return 在向其附加值后为空或显示空数组

Why does my array return null or show an empty array, after appending values to it

我正在从 firebase real-time 数据库获取值。我想将这些值存储到一个数组中并将它们显示在 UITableView 中。这是正在发生的事情:


我在 viewDidLoad() 函数之前定义了数组,如下所示:

var taskTitles: [Task] = [] 

在我的 viewDidLoad() 函数中,我正在调用另一个函数来生成数组:

override func viewDidLoad() {
    super.viewDidLoad()
    
    //Setting the Title for the nav bar
    title = "To Do List"

    configureNavigationItems()

    taskTitles = createArray() // creating the array of tasks in db
    
    tableView.delegate = self
    tableView.dataSource = self
    
    
    
}

在这个函数中,我将信息传递给我的 类。任务和任务单元。他们只是简单地处理任务的标题。

    func createArray() -> [Task] {
        
        
        taskRef = Database.database().reference(withPath: "Tasks")
        
        //getting values from db, storing them in an array.
        refHandle = taskRef?.observe(DataEventType.value, with: { snapshot in
            for taskSnapshot in snapshot.children {
                let nodeA = taskSnapshot as! DataSnapshot
                let keyA = nodeA.key
                let theTask = Task(title: String(keyA))
                self.taskTitles.append(theTask)
                print("In the FOR Loop --> ", self.taskTitles)
            }
            print("outside of FOR  Loop --> ", self.taskTitles)
        })
        print("outside of observe func --> ", taskTitles)
        
        return taskTitles
    
    }
}

但是,它似乎没有将我的项目保存到数组中。我做了一些调试以找出问题所在。希望下图能说明问题:


知道问题出在哪里吗?

您对 taskRef?.observe 的调用是异步的。这就是为什么您会在其他行之前看到“outside of observe func --> []”。

发生的事情是您的 createArray() 函数调用 observe 然后 returns taskTitles 仍然是空的。然后您的视图完成加载并显示(大概)一个空的 table。在此之后 observe 函数使用快照调用您的闭包并更新 taskTitles,但此时 tableView 已经在屏幕上并且为空,您将不得不采取进一步的操作来重新加载它(例如,在其上调用 reloadData())。

也许还值得一提的是,您正在该函数中修改 属性,然后将其返回,并将其分配给自身。这可能是多余的。