2016-07-26 18 views
-1

这是我第一次使用堆栈溢出。我试图让我的程序在继续前等待查询任务完成,但我从来没有得到它的行为正确。我在打印报表中进行调试。第二次和第三次打印总是在第一次打印之前出现。我认为我不太了解dispatch_sync。任何帮助将不胜感激!如何在swift中使用dispatch_sync?

 let concurrentQueue = dispatch_queue_create(
      "com.x.TinderClone.queue", DISPATCH_QUEUE_CONCURRENT) 

     dispatch_sync(concurrentQueue) { 
      usersRef.queryOrderedByChild("gender").queryEqualToValue(userInterestedIn).observeSingleEventOfType(.Value, withBlock: {snapshot in 
       for child in snapshot.children { 
        let uid = child.key!! 
        let gender = child.value!!["gender"] as! String 
        let id = child.value!!["id"] as! String 
        let interestedInWomen = child.value!!["interestedInWomen"] as! Bool 
        let name = child.value!!["name"] as! String 

        let potentialMatch = User(uid: uid, gender: gender, id: id, interestedInWomen: interestedInWomen, name: name) 
        listOfPotentialMatches.append(potentialMatch) //add the user struct to the array 
       } 

       print("First") // First print 

       // ... 
       }) { (error) in 
        print(error.localizedDescription) 
      } 

      print("Second") // Second Print 
     } 

     print("Third") //Third print 

回答

0

正如您发现的那样,dispatch_sync在这里并不真正帮助您。问题在于,您提供给observeSingleEventOfType的模块作为参数传递,而不是同步执行,并且只要Firebase认为合适(假设事件发生时)就会执行该模块。

使"Second""First""Third"打印将是把他们块,或者将它们放在你拨打块结束的功能,最简单的方式和。

1

observeSingleEventOfType(:withBlock:)需要一个块,其中包括大部分的代码你写,包括print("First")块是异步执行的。

换句话说,您的dispatch_sync代码调用异步代码。即时dispatch_sync代码立即运行,但它反过来调用的异步代码不会。

您必须假定传递给observeSingleEventOfType(:withBlock:)的块可能会被无序执行并相应地进行设计。

0

我以前见过这个相同的问题。最近,我找到了一个解决方法,使用定时器“等待”您的数据从Firebase中提取。这里有一个片段,你可以尝试适应你的行为后,你的观察事件:

var timer:NSTimer?

私人FUNC attemptReloadOfTable(){ self.timer?.invalidate()

self.timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(self.handleReloadTable), userInfo: nil, repeats: false) 
}