我有一个应用程序,它从parse.com数据库中提取信息并将其传递给数组。当我从while循环中println()这个数组时,它打印正常。当我尝试在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语句内打印,则返回 [] []
非常感谢任何帮助。
答案 0 :(得分:1)
问题是您还没有理解线程/异步执行的工作原理。让我们更简单。这是伪代码:
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()
设置的值,那么它还没有准备好。
asynch块是将发生的事情,将来的某个时间 - 在所有其他代码完成之后,包括{{1}的其余部分}}