取消NSOperation for for循环?

fab*_*789 4 iphone objective-c nsoperation nsoperationqueue ios

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

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

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

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;
}
Run Code Online (Sandbox Code Playgroud)

Jus*_*ers 8

子类化的一个原因NSOperation是实现正确的取消.你可以做你的方法,但它违反了几个好的设计原则.基本上,因为取消需要操作本身的协作,NSInvocationOperation所以不构建在它已经执行时取消调用(虽然它可以开始执行之前成功取消),因为运行方法不应该知道它是如何被调用的.

相反,如果您是子类NSOperation,则可以main非常轻松地将大部分此功能放入方法中:

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

    for (...) {
        // do stuff

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

@end
Run Code Online (Sandbox Code Playgroud)

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