Cancel NSOperation in for loop?

I am trying to implement a search in a background thread using NSOperation on iOS . I did not want to subclass NSOperation , so this is what I am 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, which checks if the search is in an array. Now, when I cancel NSOperation by calling cancelAllOperations , the for loop continues to work through the array. I would like to prevent this and wondered if this could be called from 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; } 
+4
source share
1 answer

One reason for the NSOperation subclass is to implement proper undo. You can make your own approach, but this violates several good design principles. In principle, since cancellation requires the cooperation of the operation itself, NSInvocationOperation not designed to cancel the call during its execution (although it can be successfully canceled before it is launched), since the current method does not need to know anything about its name.

Instead, if you are a subclass of NSOperation , you can easily add most of this function to the main method:

 @implementation MyOperation - (void)main { if ([self isCancelled]) return; for (...) { // do stuff if ([self isCancelled]) { [tmp_array release]; return; } } } @end 

Also note that you do not need to maintain your own auto-resource pool with this implementation.

+8
source

All Articles