【问题标题】:In Swift, why GCD is not working with parse?在 Swift 中,为什么 GCD 不支持解析?
【发布时间】:2015-01-31 06:56:15
【问题描述】:

我已经在In Swift, how to stop all the process until datas retrieved from parse.com in UICOLLECTIONVIEW 上问过这个问题。在执行下一个函数之前,我无法从 parse.com 检索数据。我不知道如何访问异步线程。我已将主队列声明为“first_fun()”,因此应该首先运行。同样,它首先运行,但最后结束。在此之前,下一个函数 ("second_fun()") 被执行。如何排队这个功能块?如何先完成异步线程?请检查我的代码。

我的代码如下:

override func viewDidLoad() {

println("START")
let queue : dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue, {
   dispatch_async(dispatch_get_main_queue(), { () -> Void in 
   self.first_fun()
  })
})

second_fun()
println("END")

}

//FIRST_FUN

func first_fun() {
println("FIRST CLASS TOP")
self.par_query.findObjectsInBackgroundWithBlock({(NSArray objects, NSError error) in

if (error != nil) {
     NSLog("error " + error.localizedDescription)
}
else {

println("WELCOME to PARSE")           

}//ELSE ENDING

})//PARSE ENDING
println("FIRST CLASS BOTTOM")

}

//SECOND_FUN

func second_fun() {

println("WELCOME to SECOND")

}

【问题讨论】:

    标签: swift parse-platform grand-central-dispatch


    【解决方案1】:

    您的问题的本质是“我如何将异步设计转变为同步设计”,这没有多大意义。人们在接受传统的过程式编程培训,然后尝试在基于功能/事件的系统中解决问题时,就会碰壁。

    您的问题的答案是“不要那样做”。你必须学习一种新的系统设计风格,其中在 second_fun() 中发生的一切都不依赖于 first_fun() 的结果。如果第一个和第二个真正依赖,那么您应该调用 second_fun() 作为 first_fun() 中的最后一个操作。

    例如,如果您的视图依赖于您从互联网上下载的数据(这可能是一个长时间运行的操作),您通常会将视图设置为显示旋转的等待指示器,然后您将您对 findObjectsInBackgroundWithBlock() 的调用。在回调中,您将处理找到的结果,初始化其他 UI 元素,然后将等待指示器替换为您想要的视图内容。

    你必须停止程序性思考,开始功能性思考。

    【讨论】:

      【解决方案2】:

      您可以做的是向 first_fun 添加一个回调,并在该回调中调用 second_fun,如下所示:

      func first_fun(callback: () -> ()) {
         //do something async e.g your call to parse
      
          self.par_query.findObjectsInBackgroundWithBlock({(NSArray objects, NSError error) in
              if (error != nil) {
                  NSLog("error " + error.localizedDescription)
              }
              else {
                  println("WELCOME to PARSE")           
      
              }//ELSE ENDING
              callback()
          })//PARSE ENDING
      }
      

      你的 viewDidLoad 看起来像这样:

      override func viewDidLoad() {
          let queue : dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
          dispatch_async(queue, {
              dispatch_async(dispatch_get_main_queue(), { () -> Void in
                  self.first_fun() {
                      self.second_fun()
                  }
              })
          })
      }
      

      您当然还应该参数化该回调以访问来自解析的数据或错误

      供参考:Further info for completion blocks in swift

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 2021-12-12
      • 2015-08-04
      • 1970-01-01
      相关资源
      最近更新 更多