IOS:停止方法的执行

IOS:停止方法的执行,ios,for-loop,touchesbegan,Ios,For Loop,Touchesbegan,我有以下代码: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { mouseSwiped = NO; UITouch *touch = [touches anyObject]; point =[touch locationInView:imageView]; [self openImages]; } 每次我触摸屏它叫“openImages”方法 -(无效)openImages{ //一些代码。。。。 对于

我有以下代码:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

mouseSwiped = NO;
UITouch *touch = [touches anyObject];

point =[touch locationInView:imageView];

[self openImages];
}
每次我触摸屏它叫“openImages”方法

-(无效)openImages{
//一些代码。。。。
对于(int i=0;i<200;i++){
对于(int j=0;j<200;j++){
//一些代码。。。
}                 
}
}
然后你可以看到“openImage”是一个沉重的方法,因为我打开一些uiimage时有一个双循环(但这不是问题)。 我的问题是:我能做什么来停止每次触摸屏幕时打开图像,并再次调用它(因为如果我经常触摸屏幕应用程序崩溃)。
您能帮助我吗?

您可以使用
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

哦,哦,不错!你能用外部for循环检查isCancelled吗?你能给我一个例子链接吗?或者你能举个例子吗?@Jonas Byström这取决于循环内部发生了什么。如果没有这方面的知识,我会在两个循环中检查
是否被取消!是否取消了self.isCancelled
@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
- (void)openImages {
    for (NSOperation *o in imageOperationsQueue.operations) {
        if ([o isKindOfClass:[OpenImagesOperation class]]) {
            [o cancel];
        }
    }
    [imageOperationsQueue addOperation:[OpenImagesOperation new]];
}