在Swift中,为什么GCD无法解析? [英] In Swift, why GCD is not working with parse?

查看:81
本文介绍了在Swift中,为什么GCD无法解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在在Swift中询问了如何停止所有过程,直到在UICOLLECTIONVIEW中从parse.com检索到数据为止..在执行下一个功能之前,我无法从parse.com检索数据.我不知道如何访问异步线程.我已声明主队列为"first_fun()",因此应首先运行.同样,它先运行,但最后运行.在此之前,将执行下一个函数("second_fun()").如何排队该功能块?如何先完成异步线程?请检查我的代码.

I have already asked this on In Swift, how to stop all the process until datas retrieved from parse.com in UICOLLECTIONVIEW. I couldn't retrieve the datas from parse.com before next function get executed. I don't know how to access asynchronous thread. I have declared main queue to be "first_fun()", so this should be run first. Likewise, it is running first, but ending at last. Before that, next function ("second_fun()") gets executed. How to QUEUE this function block? How to finish asynchronous thread first? Kindly check my code.

我的代码如下:

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

//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

//SECOND_FUN

func second_fun() {

println("WELCOME to SECOND")

}

推荐答案

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

What you could do is add a callback to the first_fun and call second_fun inside that callback like so:

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如下所示:

Your viewDidLoad would look like this:

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()
            }
        })
    })
}

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

You should of course also parameterize that callback to have access to the data or error from parse

供参考:快速完成区块的更多信息

这篇关于在Swift中,为什么GCD无法解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆