热门标签 | 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()
           }

    })

推荐阅读
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 本文介绍了如何在给定的有序字符序列中插入新字符,并保持序列的有序性。通过示例代码演示了插入过程,以及插入后的字符序列。 ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
author-avatar
手机用户2502896757
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有