结构数组未在闭包外部更新 [英] Array of struct not updating outside the closure
问题描述
我有一个名为displayStruct的结构数组
I have an array of struct called displayStruct
struct displayStruct{
let price : String!
let Description : String!
}
我正在从firebase读取数据并将其添加到名为myPost的结构数组中,该数组在下面初始化
I am reading data from firebase and add it to my array of struct called myPost which is initialize below
var myPost:[displayStruct] = []
我做了一个函数,可以将数据库中的数据添加到这样的struct数组中
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
})
}
如果我打印myPost.count,则在此闭包内,我得到正确的长度,但是如果我打印长度,则即使在全局声明数组的情况下,我也得到零(我认为)
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)
我在viewDidLoad方法内部调用了此方法
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
}
我想使用这个长度是我在tableView功能下的方法
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!
推荐答案
Firebase observe
对数据库的调用是asynchronous
,这意味着当您请求该值时,它可能不可用,因为它可能正在处理抓取它.
Firebase observe
call to the database is asynchronous
which means when you are requesting for the value it might not be available as it might be in process of fetching it.
这就是为什么您对count
的两个查询都在viewDidLoad
和DataSource delegeate
方法中返回0的原因.
That's why your both of the queries to count
returns 0 in viewDidLoad
and DataSource delegeate
method.
databaseRef.child("Post").queryOrderedByKey().observe(.childAdded, with: { // inside closure }
在闭包内部,代码已被执行,因此您具有值.
Inside the closure, the code has been already executed and so you have the values.
您需要做的是您需要在封闭内部的主线程中重新加载Datasource
.
What you need to do is you need to reload your Datasource
in main thread inside the closure.
databaseRef.child("Post").queryOrderedByKey().observe(.childAdded, with: {
// After adding to array
DispatchQueue.main.asyc {
self.tableView.reloadData()
}
}
这篇关于结构数组未在闭包外部更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!