CellForRow被延迟调用

时间:2015-10-08 07:44:47

标签: swift uikit mapkit

每当用户位置发生重大变化时,我都会尝试从Web服务器加载数据。我的问题是,对于任何位置更改,tableview调用“numberOfRows”,但它等待30秒,直到调用“cellForRowAtIndexPath”。或者直到用户移动了表格。

我有时也会遇到随机警告:自动布局不受主队列线程影响(可能与此问题有关)

我的问题在哪里?也许我做事两次异步并不好?

这是我的代码:

import UIKit
import MapKit

class GroundListTVCTEST: UITableViewController,CLLocationManagerDelegate, UISearchBarDelegate, UISearchControllerDelegate
{

    var locationManager = CLLocationManager()
    var searchController    :TKSearchController!
    var localSearchRequest  :MKLocalSearchRequest!
    var localSearch         :MKLocalSearch!
    var localSearchResponse :MKLocalSearchResponse!
    var grounds:[Ground]? {
        didSet {
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startMonitoringSignificantLocationChanges()
        let distance:CLLocationDistance = 1000.0
        locationManager.distanceFilter = distance
    }
    override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated)
        self.locationManager.startUpdatingLocation()

        print("Location Manager started.")

    }

    override func viewWillDisappear(animated: Bool)
    {
        super.viewWillDisappear(animated)
        locationManager.stopUpdatingLocation()

        print("Location Manager stopped.")

    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        print("cellForRow called")
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
        cell?.textLabel?.text = grounds?[indexPath.row].name
        return cell!
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("number of rows called")
        return grounds?.count ?? 0
    }

    // MARK: - Delegate Methods

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
        print("Location Manager updated location.")
        if let location = manager.location {
            self.locationUpdateWithNewLocation(location)
        }
    }

    func locationUpdateWithNewLocation(location: CLLocation)
    {
        GroundHelper.getAllGroundLocations(location, completionHandler: { (grounds: [Ground]?) -> Void in
            self.grounds = grounds?.sort({$0.distance < $1.distance})
        })

    }
}

1 个答案:

答案 0 :(得分:1)

看起来那是因为GroundHelper.getAllGroundLocations在后台队列中返回值。 尝试在主队列中发送它:

 GroundHelper.getAllGroundLocations(location, completionHandler: { (grounds: [Ground]?) -> Void in
      dispatch_async(dispatch_get_main_queue(),{
            self.grounds = grounds?.sort({$0.distance < $1.distance})
      })  
 })