在for循环中取消NSOperation?
我正在尝试使用 iOS
上的 NSOperation
在后台线程上实现搜索。我不想子类化 NSOperation
所以这就是我正在做的:
[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 循环中调用它是否合法:
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;
}
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];
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
子类化 NSOperation 的原因之一是实现正确的取消。您可以采用您的方法,但它违反了一些良好的设计原则。基本上,由于取消需要操作本身的配合,因此
NSInitationOperation
并不是为了在已经执行时取消调用而构建的(尽管可以在开始执行之前成功取消它) ),因为正在运行的方法不应该知道它是如何被调用的。相反,如果您继承
NSOperation
的子类,则可以非常轻松地将大部分功能放入main
方法中:另请注意,您不必使用以下命令来维护自己的自动释放池 :这样的实施。
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.Instead, if you subclass
NSOperation
, you can put most of this functionality into themain
method very easily:Note also that you don't have to maintain your own autorelease pool with such an implementation.