Array of struct not updating outside the closure

后端 未结 2 1603
小蘑菇
小蘑菇 2021-01-25 20:27

I have an array of struct called displayStruct

struct displayStruct{
let price : String!
let Description : String!
} 

I am reading

相关标签:
2条回答
  • 2021-01-25 20:47

    You making a asynchronous network request inside closure and compiler doesn't wait for the response, so just Reload Table when get post data. replace the code with below it work works fine for you. All the best.

     func addDataToPostArray(){
            let databaseRef = Database.database().reference()
            databaseRef.child("Post").queryOrderedByKey().observe(.childAdded, with:  {
                snapshot in
    
                let snapshotValue = snapshot.value as? NSDictionary
                let price = snapshotValue?["price"] as! String
                let description = snapshotValue?["Description"] as! String
                // print(description)
                //  print(price)
    
                let postArr =  displayStruct(price: price, Description: description)
                self.myPost.append(postArr)
                print(self.myPost.count)
                print(self.myPost)
                self.tableView.reloadData()
           //if i print self.myPost.count i get the correct length
    
            })
        }
    
    0 讨论(0)
  • 2021-01-25 20:53

    Firebase observe call to the database is asynchronous which means when you are requesting for the value it might not be available as it might be in process of fetching it.

    That's why your both of the queries to count returns 0 in viewDidLoad and DataSource delegeate method.

      databaseRef.child("Post").queryOrderedByKey().observe(.childAdded, with:  { // inside closure }
    

    Inside the closure, the code has been already executed and so you have the values.

    What you need to do is you need to reload your Datasource in main thread inside the closure.

       databaseRef.child("Post").queryOrderedByKey().observe(.childAdded, with:  { 
           // After adding to array
           DispatchQueue.main.asyc {
               self.tableView.reloadData()
           } 
    
        }
    
    0 讨论(0)
提交回复
热议问题