gpt4 book ai didi

ios - 在 Swift 中访问函数外部的变量

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

我想访问此函数外部的“posts”,以便我可以在函数外部调用 tableview.reloaddata() 。每次有键进入 qeoquery 时,下面的代码都会调用 tableview.reloaddata() 。我只想重新加载一次。但是当我尝试 viewDidLoad 时,“posts”数组为空。该怎么办?

在函数外部声明的帖子:

var  posts = [Post]()

功能:

func fetchData(){


geofireRef = Database.database().reference().child("LOCATION")
geofire = GeoFire(firebaseRef: geofireRef)
let geoQuery = geofire?.query(at: myLoc, withRadius: 5.0)

geoQuery?.observe(.keyEntered, with: { (key: String!, location: CLLocation!) in
print("KEYKEY: \(key)")
let dbRef = Database.database().reference().child("posts")
let query = dbRef.queryOrdered(byChild: "\(key)")
query.observeSingleEvent(of: .value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{
for snap in snapshot {
if let postDict = snap.value as? Dictionary<String, Any>{
let key = snap.key
let post = Post.init(postKey: key, postData: postDict)


self.posts.append(post)
}
}
}
//self.posts.reverse()
//self.tableView.reloadData()
//print("POSTS: \(self.posts)")
})
})
}

最佳答案

您可以在设置 posts 变量后立即调用 tableView.reloadData() (就像您已注释掉的那样),也可以在帖子上放置 didSet 观察者变量并在设置后重新加载 tableView。如果您选择第二个选项,您将需要重组解析器以仅设置帖子一次,而不是一次附加一个项目。看起来像这样:

var posts = [Post]() {
didSet {
self.tableView.reloadData()
}
}

geoQuery?.observe(.keyEntered, with: { (key: String!, location: CLLocation!) in
print("KEYKEY: \(key)")
let dbRef = Database.database().reference().child("posts")
let query = dbRef.queryOrdered(byChild: "\(key)")
query.observeSingleEvent(of: .value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{
//Create a variable to hold posts until you've parsed all of them
var foundPosts = [Post]()
for snap in snapshot {
if let postDict = snap.value as? Dictionary<String, Any>{
let key = snap.key
let post = Post.init(postKey: key, postData: postDict)
foundPosts.append(post)
}
}
//Set the posts to be all the found posts
self.posts = foundPosts
}
})
})

关于ios - 在 Swift 中访问函数外部的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47623201/

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