热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在Swift3中的另一个函数之后运行一个函数-HowtorunafunctionafteranotherfunctioninSwift3

Iamnewtoswift3,andIgotstucktothisproblem.Ihavetwofunctions,thefirstfunctiongets

I am new to swift 3, and I got stuck to this problem. I have two functions, the first function gets the value of a key in my FirebaseDatabase. The second function displays a the variable retrieved from the FirebaseDatase inside a TableView. The problem is that the second function launches before the first one. This makes the value return nil.

我是swift 3的新手,我遇到了这个问题。我有两个函数,第一个函数获取FirebaseDatabase中键的值。第二个函数显示从TableView内的FirebaseDatase检索的变量。问题是第二个函数在第一个函数之前启动。这使得值返回为零。

First function:

        self.shopItems = [String]()



        databaseRef.observe(FIRDataEventType.value, with: { (snapshot) in
                for child in snapshot.children {
                    let snap = child as! FIRDataSnapshot
                    let dictiOnary= snap.value as! [String: AnyObject]
                    self.shopItems.append(dictionary["Name"] as! String)

                    print(self.shopItems)
            }

        })

The second function:

第二个功能:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: self.cellReuseIdentifier, for: indexPath) as UITableViewCell

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
        cell.textLabel?.text = self.shopItems[indexPath.row]
    })
    return cell
}

I know i can use the Dispatch-Wait method, but I want the second function to wait until the first one is done. How would i do so?

我知道我可以使用Dispatch-Wait方法,但是我希望第二个函数等到第一个函数完成。我该怎么办?

3 个解决方案

#1


2  

Try with this, as I said in my first comment I think you only need call self.tableView.reloadData after print(self.shopItems)

试试这个,正如我在第一篇评论中所说,我认为你只需要在打印后调用self.tableView.reloadData(self.shopItems)

self.shopItems = [String]()
databaseRef.observe(FIRDataEventType.value, with: { (snapshot) in
    for child in snapshot.children {
        let snap = child as! FIRDataSnapshot
        let dictiOnary= snap.value as! [String: AnyObject]
        self.shopItems.append(dictionary["Name"] as! String)

        print(self.shopItems)
    }
    self.tableView.reloadData()
})

And correctly implement this method

并正确实现此方法

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.shopItems.count
}

Also update your cellForRow to this

还要将cellForRow更新为此

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: 
    self.cellReuseIdentifier, for: indexPath) as UITableViewCell

    cell.textLabel?.text = self.shopItems[indexPath.row]
    return cell
}

Hope this helps

希望这可以帮助

#2


1  

You are badly confused. You don't call tableView(_:cellForRowAt:). The system calls it.

你非常困惑。你不要调用tableView(_:cellForRowAt :)。系统调用它。

If you want to wait and reload your table once the data has finished loading, you should put a call to reloadData inside your databaseRef.observe method's closure:

如果要在数据加载完成后等待并重新加载表,则应在databaseRef.observe方法的闭包内调用reloadData:

    databaseRef.observe(FIRDataEventType.value, with: { (snapshot) in
            for child in snapshot.children {
                let snap = child as! FIRDataSnapshot
                let dictiOnary= snap.value as! [String: AnyObject]
                self.shopItems.append(dictionary["Name"] as! String)

                print(self.shopItems)

                //Add the line below. 
                //Note that if the closure is called from the background, you'll 
                //need to use GCD to call this method on the main thread.
        }
        self.tableView.reloadData()
    }

And, if the completion code in your databaseRef.observe method gets called on a background thread then you'll need to wrap that in a call to Dispatch.main.async() (or a similar method to invoke the code on the main thread.)

并且,如果在后台线程上调用databaseRef.observe方法中的完成代码,则需要在调用Dispatch.main.async()时调用它(或者在主线程上调用代码的类似方法) 。)

DispatchQueue.main.async() {
    self.tableView.reloadData()
}

#3


0  

The second function runs when data in the tableview is loaded. When the tableview is created it loads the data from shopitems array into the view. If there are no objects in the array the tableview will appear empty. In order to reflect changes to the shopitems array, in other words reflect that in item has been appended to the array you have to call the appropriate tableview function .

第二个函数在加载tableview中的数据时运行。创建tableview后,它会将shopitems数组中的数据加载到视图中。如果数组中没有对象,则tableview将显示为空。为了反映shopitems数组的更改,换句话说,反映在项目中已经附加到数组,您必须调用相应的tableview函数。

The correct way to do this is to use:

正确的方法是使用:

    databaseRef.observe(FIRDataEventType.value, with: { (snapshot) in
            for child in snapshot.children {
                let snap = child as! FIRDataSnapshot
                let dictiOnary= snap.value as! [String: AnyObject]
                self.shopItems.append(dictionary["Name"] as! String)

                let row = self.shopItems.index(of:self.shopItems.last!)
                let indexPath = IndexPath(row:row, section:0)
                tableView.insertItemsAtIndexPaths([indexPath])

                print(self.shopItems)
        }

    })

.You will have to create an indexPath using the index of the object in the shopitems array.

。您将必须使用shopitems数组中对象的索引创建indexPath。

The other method is to reload all the data in the tableview after append.

另一种方法是在追加后重新加载tableview中的所有数据。

    databaseRef.observe(FIRDataEventType.value, with: { (snapshot) in
            for child in snapshot.children {
                let snap = child as! FIRDataSnapshot
                let dictiOnary= snap.value as! [String: AnyObject]
                self.shopItems.append(dictionary["Name"] as! String)



                print(self.shopItems)
        }

              DispatchQueue.main.async {
            self.tableView.reloadData()
           }

    })

推荐阅读
author-avatar
杨barkema_252
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有