Home > Back-end >  Why does my array return null or show an empty array, after appending values to it
Why does my array return null or show an empty array, after appending values to it

Time:11-18

I am getting values from a firebase real-time database. I want to store these values into an array and display them in a UITableView. Here is what is happening:


I have defined the Array before my viewDidLoad() function as the following:

var taskTitles: [Task] = [] 

In my viewDidLoad() function I am calling another function to generate the array:

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
    
    
    
}

In this function, I am passing information to my classes. Task and TaskCell. They are simply just handling the Title of the task.

    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
    
    }
}

However, it doesn't seem to save my items into the array. I did some debugging to figure where things were going wrong. Hopefully, the picture below can clarify:enter image description here


Any idea what the issue is?

CodePudding user response:

Your call to taskRef?.observe is asynchronous. That is why you see "outside of observe func --> []" printed before the other lines.

What is happening is that your createArray() function calls observe and then returns taskTitles which is still empty. Then your view finishes loading and shows (presumably) an empty table. After this the observe function calls your closure with the snapshot and you update taskTitles, but at this point tableView is already on screen and empty and you would have to take further actions to reload it (like, for example, calling reloadData() on it).

It is perhaps also worth mentioning that you are modifying your property in that function, then returning it, and assigning it to itself. This is perhaps redundant.

  • Related