我正在尝试从MySQL数据库中检索信息并处理数据。问题是检索是通过NSURLSessions异步完成的,并且在数据返回之前打印了更新/控制台输出。
我通过dispatch_group_notify使用dispatch_group_enter / dispatach_group_leave来部分解决了上述问题。使用此设置解决了控制台输出,但我无法传递值(我的理解是我不能在dispatch_group_notify闭包内部生成一个return语句)
MySQLCommunications.swift:
Class DBcom {
var dbGetQueue = dispatch_group_create()
func getMaxValue () -> Int {
var neverGetsFilled = getDBdata()
//process the self.DBTaskResults to extract Int (not neverGetsFilled)
dispatch_group_notify(self.dbGetQueue, dispatch_get_main_queue(), {
//1. Can print result here ok
//2. Cannot return result inside closure.
}
return result
}
func getDBData () ->NSData {
dispatch_group_enter(self.dbGetQueue)
let getDBTask = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest,
completionHandler: {(reqData,reqResponse, reqError) -> Void in
self.DBTaskResults = reqData
dispatch_group_leave(self.dbGetQueue)
})
getDBTask.resume()
return self.DBTaskResults
}
}
TempTestController.swift:
class TempTestViewController: UIViewController {
@IBAction func TestButtonPressed(sender: AnyObject) {
let testDB = DBcom()
var maxfloor = testDB.getMaxValue()
println(maxfloor) //this is empty
}
}
我正在尝试保留与从数据库中检索数据相关的所有内容" MySQLCommunications.swift"功能返回相关数据。但是:
var myEmptyDBReturn = testDB.getMaxValue()
是空的。我可以在AppDelegate.swift中使用在@UIApplicationMain行上面声明的全局变量并执行:
globalVar = getMaxValue.processed_results //done inside dispatch notify in DBcom.getMaxValue
获取MySQLCommunications.swift之外的值,但它并没有解决时间问题。从本质上讲,我想知道如何将从异步任务派生的值分配给某个变量,这样当我使用该变量时,它就会有检索到的数据。
答案 0 :(得分:1)
方法dispatch_group_notify()将立即返回,而不等待组中的所有块。传递给dispatch_group_notify()的块将在该特定组中的所有块完成时执行。
您可能需要在getMaxValue()方法中放置一个回调函数,该函数将在执行通知块时被调用。
OR
如果您不担心调用线程被阻止,那么您可以使用dispatch_group_wait(),如下例所示:
func getMaxValue () -> Int {
var neverGetsFilled = getDBdata()
//process the self.DBTaskResults to extract Int (not neverGetsFilled)
dispatch_group_wait(self.dbGetQueue, DISPATCH_TIME_FOREVER)
//You will reach here only when all the group blocks are executed.
return result
}