简体   繁体   English

在Swift中访问外部变量

[英]Accessing variable outside function in Swift

I want to access "posts" outside this function so that I can call tableview.reloaddata() outside the function. 我想在此函数外部访问“帖子”,以便可以在函数外部调用tableview.reloaddata()。 The code under calls tableview.reloaddata() everytime a key has entered the qeoquery. 每次键进入qeoquery时,调用tableview.reloaddata()下的代码。 I want to only reload it one time. 我只想重新加载一次。 But when I try in viewDidLoad, the "posts" array is empty. 但是,当我尝试使用viewDidLoad时,“ posts”数组为空。 What to do? 该怎么办?

Posts declared outside function: 在函数外部声明的帖子:

var  posts = [Post]()

Function: 功能:

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)")
            })
        })
    }

You can either call tableView.reloadData() right after setting your posts variable (like you have commented out), or you can put a didSet observer on your posts variable and reload your tableView after it's set. 您可以在设置posts变量后立即调用tableView.reloadData() (就像您已注释掉一样),也可以在didSet变量上放置didSet观察器,然后在设置tableView之后重新加载它。 If you go with that second option you'll want to restructure your parser to set the posts only once, rather than appending items one at a time. 如果使用第二个选项,则将需要重组解析器以仅设置一次帖子,而不是一次附加一项。 That would look something like this: 看起来像这样:

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
            }
        })
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM