我有这个代码:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
mouseSwiped = NO;
UITouch *touch = [touches anyObject];
point =[touch locationInView:imageView];
[self openImages];
}
每次触摸屏幕时它都会调用“openImages”方法;
- (void) openImages{
// some code....
for(int i = 0; i < 200; i++){
for(int j = 0; j < 200; j++){
//some code...
}
}
}
然后您可以看到“openImage”是一个繁重的方法,因为在我打开一些 uiimage 的地方有一个双循环(但这不是问题所在)。 我的问题是:我可以做些什么来在每次触摸屏幕时停止 openImages,并再次调用它(因为如果我经常触摸屏幕应用程序崩溃)。 你能帮帮我吗?
最佳答案
为此,您可以使用 NSOperationQueue
。使openImages
成为可以取消的操作。每次触摸时,您都可以从队列中获取所有“打开图像”操作,取消它们并将新操作排队。
详细说明:
为您的队列创建一个实例变量并在执行任何操作之前对其进行初始化:
imageOperationsQueue = [NSOperationQueue new];
操作可以这样实现:
@interface OpenImagesOperation : NSOperation
@end
@implementation OpenImagesOperation
- (void)main {
for (int i = 0; !self.isCancelled && i < 200; i++) {
for (int j = 0; !self.isCancelled && j < 200; j++) {
//some code...
}
}
}
@end
openImages
方法现在看起来像
- (void)openImages {
for (NSOperation *o in imageOperationsQueue.operations) {
if ([o isKindOfClass:[OpenImagesOperation class]]) {
[o cancel];
}
}
[imageOperationsQueue addOperation:[OpenImagesOperation new]];
}
关于IOS:在执行过程中停止方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9192407/