问题描述
我有一个 while循环,正在检查Firebase菜单上的某些价格。对于每一项,它会转到一个特定的引用URL并获取该菜的价格,然后将其值提交到要在表上显示的数组。
I have a 'while' loop that is checking Firebase for some prices on a menu. For each item, it goes to a specific ref URL and grabs that dish's price, then commits it's value to an array to be displayed on a table.
var i = 0
while i < self.itemNames.count {
itemNameRef.childByAppendingPath("\(self.itemNames[i])/itemPrice").observeEventType(.Value, withBlock: {
snapshot in
self.itemPrices.append(snapshot.value as! String)
})
i++
}
事实是,一旦退出了watchEventType外壳,似乎就清除了我的整个数组。我在整个循环中放置了一些print()语句,发现如果该语句位于附加代码的正下方,但在})之外,我可以获取它以在附加数组时打印该数组,它仅返回一个空数组。
Thing is, it seems to clear my entire array once it exits the observeEventType enclosure. I've placed some print() statements throughout the loop, and found that I can get it to print the array as it appends if the statement is directly beneath the appending code, but outside the }), it only returns an empty array.
这是怎么回事?谢谢!
推荐答案
observeEventType
方法有什么作用?
从将阻止/关闭作为参数的事实,它向我暗示这是一个异步函数(该函数在后台线程上启动长时间运行的任务,然后立即返回,在后台任务完成之前。最后,它会在长时间运行的任务完成时调用完成阻止/关闭操作。)
From the fact that it takes a block/closure as a parameter, it suggests to me that it is an async function (A function that starts a long-running task on a background thread, then returns immediately, before the background task completes. Finally, it calls the completion block/closure when the long-running task completes.)
You是大学教授。您将一堆考试交给助教,然后说:请给这些分数打分,完成后在计算机中输入分数。
You are a college professor. You hand a stack of exams to your teaching assistant and say "Please grade these and enter the grades into the computer once you're done."
如果,当您的助手走向空荡荡的教室开始为考试评分,您登录并检查考试成绩,是否可以输入?当然不是。助理甚至还没有坐下!
If, as your assistant walks towards an empty classroom to begin grading exams, you log into the your and check the exam grades, will they be entered? Of course not. The assistant hasn't even sat down yet!
为这些考试打分是一项长期的任务。 并在完成后将其输入到计算机中是结束块/结束符。
The "go grade these exams" is the long-running task. The "And enter them into the computer once you're done" is the completion block/closure.
如果您调用异步函数,则在下一行中查找结果,它们将不存在。
If you call an async function, then on the next line, look for the results, they won't be there.
您必须将在任务完成后立即运行的代码放入完成块/闭包中(Objective-C称其为块。Swift称其为闭包。其他语言称它们为lambda或匿名函数。)
You have to put code that runs once the task is completed inside the completion block/closure (Objective-C calls them blocks. Swift calls them closures. Other languages call them lambdas or anonymous functions.)
这篇关于退出“ while”循环后,数组项会被删除吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!