gpt4 book ai didi

arrays - 加载数组中的数据

转载 作者:行者123 更新时间:2023-11-28 14:22:15 25 4
gpt4 key购买 nike

当我进入 View Controller 时,我想在数组中加载数据。当我打印数组时,它是空的,但是如果我使用刷新并再次打印数组,他就会被加载。它是代码:

var information = [String]()

override func viewDidLoad() {
super.viewDidLoad()
loadinformation()
print(information)
}

func loadinformation() {
let ref = Database.database().reference()
let uid = Auth.auth().currentUser?.uid
let prof = ref.child("users").child(uid!).child("interess")
prof.observeSingleEvent(of: .value,with: { (snapshot) in
if let dict = snapshot.value as? [String: Any] {
let name = dict["FullName"] as! String
self.information.append(name)
}
})


}

最佳答案

这一行

prof.observeSingleEvent(of: .value,with: { (snapshot) in

是异步的,这意味着它不作为代码的串行流运行,你需要在这里打印它

let name = dict["FullName"] as! String
self.information.append(name)
print(self.information)

//

或者使用补全

func loadinformation(completion:@escaping(_ arr:[String]?) -> Void ) {
var arr = [String]()
let ref = Database.database().reference()
let uid = Auth.auth().currentUser?.uid
let prof = ref.child("users").child(uid!).child("interess")
prof.observeSingleEvent(of: .value,with: { (snapshot) in
if let dict = snapshot.value as? [String: Any] {
let name = dict["FullName"] as! String
arr.append(name)
completion(arr)
}
else {
completion(nil)
}
})

}

打电话

loadinformation { (result) in
print(result)
if let content = result {
self.information = content
self.collectionView.reloadData()
}
}

关于arrays - 加载数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51831593/

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