Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 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 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...