等待异步函数完成

Wait for Asynchronous Function to Complete

位置管理器需要一段时间来查询 class 10000 行(在 Parse 中)。 我试图阻止用户在查询完成之前选择一行(在 tableViewController 中)。 在允许选择之前强制用户等待查询完成的最佳方法是什么?

加载数据的查询:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
        if (error != nil) {
            println("Error:" + error.localizedDescription)
        }
        if placemarks.count > 0 {
            let pm = placemarks[0] as CLPlacemark
            self.displayLocationInfo(pm)
            currentLoc = manager.location
            currentLocGeoPoint = PFGeoPoint(location:currentLoc)

            var query = PFQuery(className:"test10000")
            query.whereKey("RestaurantLoc", nearGeoPoint:currentLocGeoPoint, withinMiles:10) //filter by miles
            query.limit = 1000 //limit number of results
            query.findObjectsInBackgroundWithBlock {
                (objects: [AnyObject]!, error: NSError!) -> Void in
                if objects != nil {
                    unfilteredRestaurantArray = objects
                } else {
                    println("error: \(error)")
                }
            }

        } else {
            println("error: \(error)")
        }
    })
}

附加信息:

该程序将 didSelectRowAtIndex 与 segues 结合使用:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.row == 0 {
        self.performSegueWithIdentifier("toQ2", sender: self)
    } else {
        self.performSegueWithIdentifier("toQ1", sender: self)
    }

viewDidLoad 调用 locationManager:

override func viewDidLoad() {
    self.locationManager.delegate = self //location manager start
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
}

自己定义一个变量,表示查询仍然是 运行。当您开始查询时,禁用与 table 的任何交互或在其上放置一个带有 activity 指示符的叠加层。要在查询完成时得到通知,您可以使用 didSet 挂钩,例如

var queryIsRunning : Bool { didSet { onQueryIsRunningChanged() } }

[...]

func onQueryIsRunningChanged()
{
    if queryIsRunning
    {
        // Code to disable user interactions
    }
    else
    {
        // Code to re-enable user interactions
    }
}

也许需要从主线程设置变量,这可以通过

dispatch_async(dispatch_get_main_queue(), { self.queryIsRunning = queryIsRunningState } )