我正在尝试从MySQL数据库检索信息并处理数据。问题是检索是通过NSURLSessions异步完成的,并且在数据返回之前打印更新/控制台输出。
我已经通过使用带有dispatch_group_notify的dispatch_group_enter/dispatach_group_leave部分解决了上述问题。使用此设置可以解决控制台输出问题,但我不能传递该值(我的理解是,我不能在dispatch_group_notify闭包内执行返回语句)
设置:
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之外的值,但这并不能解决计时问题。本质上,我想知道如何将从异步任务派生的值赋给某个变量,以便当我使用该变量时,它具有检索到的数据。
发布于 2015-04-09 10:34:08
方法dispatch_group_notify()将立即返回,而不等待组中的所有块。传递给dispatch_group_notify()的块将在该特定组中的所有块完成时执行。
您可能需要在getMaxValue()方法中放置一个回调,该方法将在notify块执行时被调用。
或
如果你不担心调用线程会被阻塞,那么你可以像下面的例子一样使用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
}
https://stackoverflow.com/questions/29535757
复制相似问题