我有一个应用程序,它从 parse.com 数据库中提取信息并将其传递到数组中。当我从 while 循环内部打印ln() 这个数组时,它打印正常。当我尝试在 while 循环之外打印它时,它返回为空。这是我的代码:
var players = [String]()
var total = [String]()
var addTotal:AnyObject!
var addTotalFinal:Int!
var addPlayers:AnyObject!
var addPlayersFinal:Array<Int>!
@IBOutlet weak var tableView: UITableView!
var test: AnyObject!
override func viewDidLoad() {
super.viewDidLoad()
Parse.setApplicationId("KZ758LUTQZQ9Kl69mBDkv7BNLGHyXeKmqtFf7GmO", clientKey: "lOK5rg7wKeTRXZGV7MZBlQ5PTpNlGO0mkgtLkLgH")
var query = PFQuery(className:"runningTotal")
query.whereKey("total", notEqualTo: 0)
query.findObjectsInBackgroundWithBlock
{
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil
{
var i = 0
while i < objects.count
{
self.addTotal = objects[i]["total"]
self.addTotalFinal = self.addTotal as Int
self.addPlayers = objects[i]["players"]
self.addPlayersFinal = self.addPlayers as Array
self.players.append("(self.addPlayersFinal)")
self.total.append("(self.addTotalFinal)")
++i
}
}
else
{
}
}
navigationItem.title = "(players)"
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return players.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel.text = "(players[indexPath.row]) - (total[indexPath.row])"
return cell
}
while 语句中的 println() 返回
[[1, 11, 12, 24, 25]]
[2]
[[1, 11, 12, 24, 25], [1, 5, 24, 25, 31]]
[2, 4]
[[1, 11, 12, 24, 25], [1, 5, 24, 25, 31], [2, 12, 25, 15, 31]]
[2, 4, -1]
[[1, 11, 12, 24, 25], [1, 5, 24, 25, 31], [2, 12, 25, 15, 31], [24, 22, 25, 31, 20]]
[2, 4, -1, -6]
[[1, 11, 12, 24, 25], [1, 5, 24, 25, 31], [2, 12, 25, 15, 31], [24, 22, 25, 31, 20], [1, 2, 3, 4, 5]]
[2, 4, -1, -6, 5]
[[1, 11, 12, 24, 25], [1, 5, 24, 25, 31], [2, 12, 25, 15, 31], [24, 22, 25, 31, 20], [1, 2, 3, 4, 5], [1, 10, 11, 2, 12]]
[2, 4, -1, -6, 5, 1]
这是有道理的,因为有六个迭代。但是,如果我在 viewDidLoad 语句内打印而不是在 while 语句内打印,它会返回 [][]
任何帮助将不胜感激。
问题是你还没有理解线程/异步执行是如何工作的。让我们更简单一点。这是伪代码:
func viewDidLoad {
doStepOne() // you configure your query here
doStepTwoWithAsynchBlock {
doStepTwo() // your while loop is here
}
doStepThree() // your failing println is here
}
这将按照 doStepOne()
、 doStepThree()
、 doStepTwo()
的顺序执行。因此,如果doStepThree()
尝试获取doStepTwo()
设置的值,则它尚未准备就绪。
异步块是将来某个时候会发生的事情 - 在所有其他代码完成后,包括viewDidLoad
的其余部分。