我怎样才能添加从JSONasynchronous提取logging到数组中,只有当所有的logging在Swift中获取?
我正在为苹果地图的市场集群(这里是插件https://github.com/ribl/FBAnnotationClusteringSwift ),我想一次显示我的地图上的所有logging – 为此,我需要下载所有logging从远程web服务,将其添加到json(我已经这样做了),然后将所有提取的点添加到数组。
我的代码如下所示:
let clusteringManager = FBClusteringManager() var array:[FBAnnotation] = [] func loadInitialData() { RestApiManager.sharedInstance.getRequests { json in if let jsonData = json.array { for requestJSON in jsonData { dispatch_async(dispatch_get_main_queue(),{ if let request = SingleRequest.fromJSON(requestJSON){ let pin = FBAnnotation() pin.coordinate = CLLocationCoordinate2D(latitude: request.latitude, longitude: request.longitude) self.array.append(pin) } }) } } } }
你可以看到我将所有pin
添加到数组中,并且在某处我需要使用这个数组:
self.clusteringManager.addAnnotations(array)
我想我可以只写在我的方法loadInitialData
结束上面的行,但数组仍然是空的。 如何更改我的代码,以便在array
填充数据时调用addAnnotations
方法?
===编辑
只是一个小的附加 – 我调用viewDidLoad
的方法loadInitialData
override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self loadInitialData() }
你可能想要使用NSOperation
。 它的API有方法addDependency(:)
这就是你正在寻找。 代码可能如下所示:
let queue = NSOperationQueue() var operations : [NSOperation] = [] RestApiManager.sharedInstance.getRequests { json in if let jsonData = json.array { for requestJSON in jsonData { let newOperation = NSBlockOperation { SingleRequest.fromJSON(requestJSON){ let pin = FBAnnotation() pin.coordinate = CLLocationCoordinate2D(latitude: request.latitude, longitude: request.longitude) self.array.append(pin) } operations.append(newOperation) } } } let finalOperation = NSBlockOperation() { ///array has been populated ///proceed with it } operations.forEach { $0.addDependency(finalOperation) } operations.append(finalOpeartion) operationQueue.addOperations(operations) }