在IOS迅速增加火力点数据到一个数组 [英] Adding firebase data to an array in ios swift

查看:178
本文介绍了在IOS迅速增加火力点数据到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从火力数据库中获取数据,并把它们添加到阵列的问题。
从方法的输出打印 getNewQuote 显示数组为空,但屏幕截图显示,该标签是在 getNewQuote 的<更新/ strong>方式。

I am having issues getting data from firebase database and adding them to array. The print output from the method getNewQuote shows that the array is empty but the screenshot shows that the label was updated within the getNewQuote method.

这怎么可能发生?
有没有在事件延迟在 getNewQuote 方式导致此?
此外,它是如何的标签与第4次迭代更新的 getNewQuote 方法,而不是最后一次迭代。

How can this be happening? Is there a latency on the event in the getNewQuote method that is causing this? moreover, how is it that the label was updated with the 4th iteration of the getNewQuote method and not the last iteration.

感谢你在前进!

code 的细分结果
在循环迭代5次,做到以下几点:结果
      1.创建一个随机数结果
      2.通过随机数到方法的 getNewQuote
     (此方法从数据库中回来的数据,并追加到数组中的 quotesMessages )结果
循环的迭代之后,完整的阵列被印刷

Breakdown of Code
Iterate in loop 5 times and do the following:
1.create a random number
2. pass random number into the method getNewQuote (This method gets back the data from the database and appends into the array quotesMessages)
After the iteration of the loop, the complete array is printed

code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var message: UILabel!

    var QuoteRef:String = "https://motivatr.firebaseIO.com/quotes"

    var quotesMessages = [String]()

    /* */
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        for (var i = 0; i < 5; i++) {
            var currRandomNumber = self.createRandomNum()
            self.getNewQuote(currRandomNumber)
        }

        println("viewDidLoad, array has \(quotesMessages.description)")
    }//eom

    /* */
    override func viewWillAppear(animated: Bool) {
        println("viewWillAppear, array has  \(quotesMessages.description)")
    }

   /* */
   override func viewDidAppear(animated: Bool) {
       println("viewDidAppear, array has  \(quotesMessages.description)")
   }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /* creates a random number */
    func createRandomNum()-> Int {
        var randomNumberRange = UInt32(49)
        var UnsignedRandomNum = arc4random_uniform(randomNumberRange)
        var randomNum = Int(UnsignedRandomNum)

        return randomNum
    }

    /* gets a new data from databases */
    func getNewQuote(randomNum: Int){
        println("random number \(randomNum) created")
        //Temp var's
        var quoteText = ""
        var quoteAuthor = ""

        var DBQuoteURL = "\(QuoteRef)/\(randomNum)"
        var myRootRef =  Firebase(url:DBQuoteURL)
        myRootRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
            if snapshot.value is NSNull {
                // The value is null
            }
            else
            {
                if let quote = snapshot.value["quote"] as? String {
                    //                    println(quote)
                    quoteText = "'\(quote)'"
                    self.message.text = quoteText
                    self.quotesMessages.append(quoteText)
                }
            }
        })

        println("quote is: \(quoteText)")
    }//eom
}//eoc

从控制台输出:

random number 24 created
quote is: 
random number 18 created
quote is: 
random number 45 created
quote is: 
random number 47 created
quote is: 
random number 34 created
quote is: 
viewDidLoad, array has []
viewWillAppear, array has  []
viewDidAppear, array has  []

iPhone屏幕截图:

推荐答案

您所遇到的问题,精彩的同步方法!

You've encountered the wonderful problem of asynchronous methods!

我不知道你是否知道这一点,但一个异步件code同时运行,而其他一切源源不绝,即你的code不会等待其完成继续

I don't know if you know this, but an asynchronous piece of code runs while everything else keeps going, i.e. your code will not wait for its completion to continue.

这里发生的事情是,你的循环获取到 myRootRef.observeSingleEventOfType ... 片,启动异步调用,然后源源不绝,而不必完成了所有的即code。

What's happening here is that your loops gets to the myRootRef.observeSingleEventOfType... piece, starts the async call, and then keeps going, without necessarily having finished all of that code.

这是它如何能看起来像它会通过回路失灵,或从未得到填补,等等。

This is how it can seem like it's going through the loop out of order, or never getting filled, etc.

我不知道你想要做什么你的 self.message.text = quoteText getNewQuote ,但是在你拥有了它,它会只是最近下载报价更新标签的方式。

I'm not sure what you want to do with your self.message.text = quoteText within getNewQuote, but in the way you have it it'll just update your label with the most recently downloaded quote.

如果你想使 myRootRef.observeSingleEventOfType ... 片code之内事情发生,确保它的<$的大括号中C $ C>如果让报价= snapshot.value [引用]作为?字符串{.......} 。
如果你想使当你与你的下载完成这一点,你可以尝试反如果quotesMessages.count == 5 {...} 内的如果让或观察员或随便你吧。

If you'd like to make something happen within the myRootRef.observeSingleEventOfType... piece of code, make sure it's within the curly brackets of if let quote = snapshot.value["quote"] as? String {.......}. If you wanna make it happen when you're done with your downloads, you could try a counter if quotesMessages.count == 5 {...}, within that if let, or an observer or whatever you please.

祝你好运!

这篇关于在IOS迅速增加火力点数据到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆