IOS:在执行过程中停止方法

标签 ios for-loop touchesbegan

我有这个代码:

- (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/

相关文章:

swift - 快速获取触摸的各种坐标

iphone - 如何在 UINavigationController 中正确继承 UITableViewController?

objective-c - 单例模式实现

java - 具有求和功能的 For 循环

java - 使用双 for 循环更改 ArrayList 中的变量

javascript - HTTP/2 : stream. 使用 For-Loop 结束

ios - TouchBegan 在 iOS 12 中被调用,但在 iOS 13 中未被调用

ios - UITableViewCell 中的自定义 UIView 阻止 uitableviewcell 接收事件

ios - 从核心数据中删除图像不起作用

ios - 如何添加 Rate App 来解锁某些东西