取消NSOperation in for循环? [英] Cancel NSOperation in for loop?

查看:86
本文介绍了取消NSOperation in for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 iOS 上使用 NSOperation 在后台线程上实现搜索。我不想继承 NSOperation ,所以这就是我正在做的事情:

I am trying to implement search on a background thread using NSOperation on iOS. I didn't want to subclass NSOperation so this is what I'm doing:

[searchQueue cancelAllOperations];
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self
                                                                  elector:@selector(filterContentForSearchText:)
                                                                   object:self.searchDisplayController.searchBar.text];
[searchQueue addOperation:op];
[op release];

搜索方法包括一个for循环,用于检查搜索的内容是否在数组中。现在当我通过调用 cancelAllOperations 取消 NSOperation 时,for循环继续在数组中运行。我想阻止这一点,并想知道在for循环中调用它是否合法:

The search method includes a for loop that checks whether what is being searched is in an array. Now when I cancel the NSOperation by calling cancelAllOperations, the for loop continues to run through the array. I would like to prevent this and was wondering whether it is legit to call this from within the for loop:

if ([[[searchQueue operations] objectAtIndex:0] isCancelled]) {
    [tmp_array release];   // tmp_array is used to hold temporary results
    [pool drain];          // pool is my autorelease pool
    return;
}


推荐答案

子类化的原因之一 NSOperation 将实施正确的取消。你可以采取你的方法,但它违反了几个好的设计原则。基本上,由于取消需要操作本身的合作, NSInvocationOperation 不是为了在调用已经执行时取消调用而构建的(尽管它可以在之前成功取消 / em>它开始执行),因为运行方法不应该知道它是如何被调用的。

One of the reasons to subclass NSOperation is to implement proper cancellation. You could do your approach, but it violates several good design principles. Basically, since cancellation requires the cooperation of the operation itself, NSInvocationOperation isn't built to cancel the invocation while it's already executing (though it can be successfully cancelled before it starts executing), as the running method shouldn't know anything about how it's called.

相反,如果你继承 NSOperation ,您可以非常轻松地将大部分功能放入 main 方法中:

Instead, if you subclass NSOperation, you can put most of this functionality into the main method very easily:

@implementation MyOperation
- (void)main {
    if ([self isCancelled])
        return;

    for (...) {
        // do stuff

        if ([self isCancelled]) {
            [tmp_array release];
            return;
        }
    }
}

@end

另请注意,您不必使用此类实现维护自己的自动释放池。

Note also that you don't have to maintain your own autorelease pool with such an implementation.

这篇关于取消NSOperation in for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆