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

    })

推荐阅读
  • ASP.NET2.0数据教程之十四:使用FormView的模板
    本文介绍了在ASP.NET 2.0中使用FormView控件来实现自定义的显示外观,与GridView和DetailsView不同,FormView使用模板来呈现,可以实现不规则的外观呈现。同时还介绍了TemplateField的用法和FormView与DetailsView的区别。 ... [详细]
  • STL迭代器的种类及其功能介绍
    本文介绍了标准模板库(STL)定义的五种迭代器的种类和功能。通过图表展示了这几种迭代器之间的关系,并详细描述了各个迭代器的功能和使用方法。其中,输入迭代器用于从容器中读取元素,输出迭代器用于向容器中写入元素,正向迭代器是输入迭代器和输出迭代器的组合。本文的目的是帮助读者更好地理解STL迭代器的使用方法和特点。 ... [详细]
  • YOLOv7基于自己的数据集从零构建模型完整训练、推理计算超详细教程
    本文介绍了关于人工智能、神经网络和深度学习的知识点,并提供了YOLOv7基于自己的数据集从零构建模型完整训练、推理计算的详细教程。文章还提到了郑州最低生活保障的话题。对于从事目标检测任务的人来说,YOLO是一个熟悉的模型。文章还提到了yolov4和yolov6的相关内容,以及选择模型的优化思路。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • LeetCode笔记:剑指Offer 41. 数据流中的中位数(Java、堆、优先队列、知识点)
    本文介绍了LeetCode剑指Offer 41题的解题思路和代码实现,主要涉及了Java中的优先队列和堆排序的知识点。优先队列是Queue接口的实现,可以对其中的元素进行排序,采用小顶堆的方式进行排序。本文还介绍了Java中queue的offer、poll、add、remove、element、peek等方法的区别和用法。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 本文介绍了在Vue项目中如何结合Element UI解决连续上传多张图片及图片编辑的问题。作者强调了在编码前要明确需求和所需要的结果,并详细描述了自己的代码实现过程。 ... [详细]
  • 本文介绍了Swing组件的用法,重点讲解了图标接口的定义和创建方法。图标接口用来将图标与各种组件相关联,可以是简单的绘画或使用磁盘上的GIF格式图像。文章详细介绍了图标接口的属性和绘制方法,并给出了一个菱形图标的实现示例。该示例可以配置图标的尺寸、颜色和填充状态。 ... [详细]
  • 本文介绍了如何使用n3-charts绘制以日期为x轴的数据,并提供了相应的代码示例。通过设置x轴的类型为日期,可以实现对日期数据的正确显示和处理。同时,还介绍了如何设置y轴的类型和其他相关参数。通过本文的学习,读者可以掌握使用n3-charts绘制日期数据的方法。 ... [详细]
  • 本文介绍了利用ARMA模型对平稳非白噪声序列进行建模的步骤及代码实现。首先对观察值序列进行样本自相关系数和样本偏自相关系数的计算,然后根据这些系数的性质选择适当的ARMA模型进行拟合,并估计模型中的位置参数。接着进行模型的有效性检验,如果不通过则重新选择模型再拟合,如果通过则进行模型优化。最后利用拟合模型预测序列的未来走势。文章还介绍了绘制时序图、平稳性检验、白噪声检验、确定ARMA阶数和预测未来走势的代码实现。 ... [详细]
  • C++ STL复习(13)容器适配器
    STL提供了3种容器适配器,分别为stack栈适配器、queue队列适配器以及priority_queue优先权队列适配器。不同场景下,由于不同的序列式 ... [详细]
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社区 版权所有