gpt4 book ai didi

ios - 结构体数组在闭包之外不更新

转载 作者:行者123 更新时间:2023-11-30 10:55:05 25 4
gpt4 key购买 nike

我有一个名为 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
}

任何帮助将不胜感激!

最佳答案

您在闭包内发出异步网络请求,编译器不会等待响应,因此只需在获取发布数据时重新加载表即可。将代码替换为下面的代码,它对您来说效果很好。祝一切顺利。

 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

})
}

关于ios - 结构体数组在闭包之外不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54054020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com