Array of struct not updating outside the closure

后端 未结 2 1608
小蘑菇
小蘑菇 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
    
            })
        }
    

提交回复
热议问题