Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

ios - Array of struct not updating outside the closure

I have an array of struct called displayStruct

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

I am reading data from firebase and add it to my array of struct called myPost which is initialize below

var myPost:[displayStruct] = [] 

I made a function to add the data from the database to my array of struct like this

 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)
   //if i print self.myPost.count i get the correct length

    })
}

within this closure if I print myPost.count i get the correct length but outside this function if i print the length i get zero even thou i declare the array globally(I think)

I called this method inside viewDidLoad method

   override func viewDidLoad() {
   // setup after loading the view.

    super.viewDidLoad()
   addDataToPostArray()
    print(myPeople.count) --> returns 0 for some reason


  }

I want to use that length is my method below a fucntion of tableView

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
 return myPost.count --> returns 0
}

Any help would be greatly appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...