我有一个 UITextfield
和 UIButton
.例如,用户可以输入诸如“dog”或“cat”之类的搜索词,它将触发另一个在 上运行的类中的方法。自定义调度 GCD 队列 获取图像(大约 100 个左右)。
一切正常,除非用户在获取过程中决定更改并输入另一个搜索词,例如“cat”,然后按下获取按钮,我希望能够在获取时停止该线程/方法上一个搜索词中的图像。
我想过NSThread
(我以前从未使用过的东西)或 block (在方法完成运行后得到通知),但是 block 的问题是,一旦方法完成它的事情,我就会得到通知,但我需要在这里告诉它停止抓取(因为用户已决定进行另一个搜索并输入另一个搜索词)。
有人可以引用我的一些示例,关于我们如何能够在循环/方法在 上运行时停止它自定义 GCD 线程 在完成之前?提前致谢。
最佳答案
我正在使用 NSOperation
和 NSOperationQueue
在后台对 map 上的标记进行聚类,并在必要时取消操作。
对标记进行聚类的功能在 NSOperation
的子类中实现。 :
集群标记.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
您可以使用 Controller 来管理队列,
self.operationQueue = [[NSOperationQueue alloc] init];
self.operationQueue.name = @"Überalgorithmus.TheKillerApp.makemyday.com";
// make sure to have only one algorithm running
self.operationQueue.maxConcurrentOperationCount = 1;
将操作入队、终止先前的操作等,
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作为首发。
关于iOS:在进程中间停止线程/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17380796/