繁体   English   中英

结构数组不在闭包外更新

[英]Array of struct not updating outside the closure

我有一个名为 displayStruct 的结构数组

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

我正在从 firebase 读取数据并将其添加到我的名为 myPost 的结构数组中,该数组在下面初始化

var myPost:[displayStruct] = [] 

我做了一个函数来将数据库中的数据添加到我的结构数组中

 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

    })
}

在这个闭包内,如果我打印 myPost.count 我得到正确的长度但在这个函数之外如果我打印长度我得到零即使你我全局声明数组(我认为)

我在 viewDidLoad 方法中调用了这个方法

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

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


  }

我想使用那个长度是我在 tableView 函数下面的方法

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

任何帮助将不胜感激!

Firebase observe对数据库的调用是asynchronous ,这意味着当您请求该值时,它可能不可用,因为它可能正在获取它。

这就是为什么您要count两个查询在viewDidLoadDataSource delegeate方法中都返回 0 的DataSource delegeate

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

在闭包内部,代码已经被执行,所以你有值。

你需要做的是你需要在闭包内的主线程中重新加载你的Datasource

   databaseRef.child("Post").queryOrderedByKey().observe(.childAdded, with:  { 
       // After adding to array
       DispatchQueue.main.asyc {
           self.tableView.reloadData()
       } 

    }

您在闭包内发出异步网络请求,编译器不会等待响应,因此在获取发布数据时只需重新加载表。 用下面的代码替换它对你来说工作正常。 祝一切顺利。

 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

        })
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM