gpt4 book ai didi

swift - 如何从快照闭包返回数组的值并使用它来准备segue?

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

我试图在函数外部获取数组的值。但是一旦快照 block 结束,newArray 的值就会变空。即使在闭包结束后我也想访问数组的值。将准备转场的值传递到下一个 View Controller 后,该值仍然为空。

var newArray = [Any]()
func getData(refe: String) -> [Any]{

let currUser = Auth.auth().currentUser?.uid
let ref = Database.database().reference(fromURL: "MyURL").child("users/\(currUser!)/Questions/")
ref.child("\(refe)").observeSingleEvent(of: .childAdded, with:{ snapshot in

let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? DataSnapshot, let value = rest.value{
self.newArray.append(value as! Any)
}
print(self.newArray)
//This gives [test,test1,test2]

})
return newArray
// Here the Array is empty.
}

实际结果:[]

预期结果:[测试、测试1、测试2]

我也尝试过这个。

    func getData(refe: String, completion: @escaping (([Any]) -> ())) {
var newArray = [Any]()
let currUser = Auth.auth().currentUser?.uid
let ref = Database.database().reference(fromURL: "MYURL").child("users/\(currUser!)/Questions/")
ref.child("\(refe)").observeSingleEvent(of: .childAdded, with: { snapshot in

let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? DataSnapshot, let value = rest.value{

newArray.append(value)
}

completion(newArray)
})
}

并在辅助函数中调用它

func getDataD() -> [Any]{
let ref = getReference()
var arr = [Any]()
self.getData(refe: ref) { (array) in
arr = array
// This gives [test,test1,test2]
}
return arr
// This gives []
}

之后调用准备segue的函数

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

guard let detailViewController = segue.destination as? HostOptionTableViewController
else {
return
}
detailViewController.ref = getReference()
self.getData(refe: detailViewController.ref) { (array) in
detailViewController.data = array
}
}
}

detailViewController.data执行后的实际结果应该是[test,test1,test2]但这是[]

最佳答案

prepareForSegue 中调用 getData 已经太晚了,这应该位于导航到第二个 vc 的操作内

 self.getData(refe:yourRef) { array in   
self.performSegue(withIdentifier:"segueName",sender:array)
}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

guard let detailViewController = segue.destination as? HostOptionTableViewController
else {
return
}
detailViewController.ref = getReference()
detailViewController.data = sender as! [Model] // Model is type of array
}

请求是异步的,导航将在获取数据之前发生

关于swift - 如何从快照闭包返回数组的值并使用它来准备segue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57304557/

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