2017-05-24 110 views
0

我想运行下面的代码,但由于某种原因,快照从不运行作为while循环的结果。当我添加while循环时,唯一打印的是"current count is <2",因为上面的currentCount的分配由于某种原因被跳过。下面是代码:代码跳过firebase快照

override func viewDidLoad() { 
    //below sets the default selection as pitcher 
    pitcher = true 
    batter = false 
    //******Needs to show the default selection as well 
    batterCheck.hidden = true 
    batterButton.tintColor = UIColor.blueColor() 
    pitcherButton.tintColor = UIColor.blueColor() 

    //below defaults to hiding the results related data 
    ResultsLabel.hidden = true 
    playName.hidden = true 
    pointDiff.hidden = true 

    var playRef = ref.child("LiveGames").child("05-25-17").child("RedSox") 
    playRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in 
     self.currentCount = Int(snapshot.childrenCount) 
     print(snapshot.childrenCount) 
     print(snapshot) 
     print("***" + String(self.currentCount)) 
    }) 

    while(self.ended != true) { 
     if(self.currentCount < 2) { 
      print("current count is < 2") 

     } else { 
      playRef.child(String(self.currentCount-2)).observeSingleEventOfType(.Value, withBlock: { (snapshot2) in 
       var hitterRef = snapshot2.childSnapshotForPath("/Hitter") 
       var pitcherRef = snapshot2.childSnapshotForPath("/Pitcher") 
       self.batterName.text = (String(hitterRef.childSnapshotForPath("/fName")) + " " + String(hitterRef.childSnapshotForPath("/lname"))) 
       self.pitcherName.text = (String(pitcherRef.childSnapshotForPath("/fName")) + " " + String(pitcherRef.childSnapshotForPath("/lname"))) 

      }) 
      self.currentCount += 1 
     } 
    } 
    print("labels updated") 

} 

然而,当我注释掉while循环CURRENTCOUNT设置为正确的值。关于这个while循环做什么来阻止Firebase快照运行的想法?

回答

2

observeSingleEventOfType:withBlock被异步调用。这意味着它将在另一个线程中执行,而不是在ViewDidLoad方法的范围内。

如果你在完成块外面附加一个断点,在完成块里面附加一个断点,它将变得更加清晰。

如果您需要在'observeSingleEventOfType'完成后更新标签,您需要执行的操作是,应该在单独的方法中移动'更新'代码并在observeSingleEventOfType方法的完成块中调用它。

实施例:

override func viewDidLoad() { 
//Your code here... 
var playRef = ref.child("LiveGames").child("05-25-17").child("RedSox") 
    playRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in 
     self.currentCount = Int(snapshot.childrenCount) 
     self.updateLabels() 
    }) 
    //Your code here... 
} 
func updateLabels() { 
    //Your update code here... 
}