我使用NSOperation
和NSOperationQueue
在後臺對地圖上的標記進行聚類,並在必要時取消操作。
ClusterMarker.h:
@class ClusterMarker;
@protocol ClusterMarkerDelegate <NSObject>
- (void)clusterMarkerDidFinish:(ClusterMarker *)clusterMarker;
@end
@interface ClusterMarker : NSOperation
-(id)initWithMarkers:(NSSet *)markerSet delegate:(id<ClusterMarkerDelegate>)delegate;
// the "return value"
@property (nonatomic, strong) NSSet *markerSet;
// use the delegate pattern to inform someone that the operation has finished
@property (nonatomic, weak) id<ClusterMarkerDelegate> delegate;
@end
和ClusterMarker.m:
@implementation ClusterMarker
-(id)initWithMarkers:(NSSet *)markerSet delegate:(id<ClusterMarkerDelegate>)delegate
{
if (self = [super init]) {
self.markerSet = markerSet;
self.delegate = delegate;
}
return self;
}
- (void)main {
@autoreleasepool {
if (self.isCancelled) {
return;
}
// perform some Überalgorithmus that fills self.markerSet (the "return value")
// inform the delegate that you have finished
[(NSObject *)self.delegate performSelectorOnMainThread:@selector(clusterMarkerDidFinish:) withObject:self waitUntilDone:NO];
}
}
@end
您可以使用您的控制器來管理 集羣標記功能是在NSOperation
一個子類實現排隊,
self.operationQueue = [[NSOperationQueue alloc] init];
self.operationQueue.name = @"Überalgorithmus.TheKillerApp.makemyday.com";
// make sure to have only one algorithm running
self.operationQueue.maxConcurrentOperationCount = 1;
排隊工作ations,殺了以前的操作等,
ClusterMarker *clusterMarkerOperation = [[ClusterMarker alloc] initWithMarkers:self.xmlMarkerSet delegate:self];
// this sets isCancelled in ClusterMarker to true. you might want to check that variable frequently in the algorithm
[self.operationQueue cancelAllOperations];
[self.operationQueue addOperation:clusterMarkerOperation];
當操作完成向回調回應:
- (void)clusterMarkerDidFinish:(ClusterMarker *)clusterMarker
{
self.clusterMarkerSet = clusterMarker.markerSet;
GMSProjection *projection = [self.mapView projection];
for (MapMarker *m in self.clusterMarkerSet) {
m.coordinate = [projection coordinateForPoint:m.point];
}
// DebugLog(@"now clear map and refreshData: self.clusterMarkerSet.count=%d", self.clusterMarkerSet.count);
[self.mapView clear];
[self refreshDataInGMSMapView:self.mapView];
}
如果我沒有記錯我以前this tutorial on raywenderlich.com作爲首發。
如果您使用'NSOperation',您需要確保在代碼中檢查isCancelled以檢測何時中止。 – mttrb