问题
Wondering if I'm implementing the below method correctly because isCancelled
is not canceling the thread. I have an image that I'm scaling, and when it's done scaling, this method is called to update the image. So when the user lifts their finger off the button, this is called. If they try to push the button again before this is finished, I call cancelAllOperations
on the queue but it's not working. Not even sure if cancelAllOperations triggers a flag, or if I need to keep calling it to get a result. Anyone have any insight on this?
- (void) refreshImage
{
NSBlockOperation *operation = [[NSBlockOperation alloc] init];
__unsafe_unretained NSBlockOperation *weakOperation = operation;
[operation addExecutionBlock:
^{
UIImage *image = [[self.graphicLayer imageForSize:self.size] retain];
if (![weakOperation isCancelled])
{
[[NSOperationQueue mainQueue] addOperationWithBlock:
^{
self.image = image;
[image release];
}];
}
else
{
[image release];
return;
}
}];
[self.queue addOperation: operation];
[operation release];
}
回答1:
Found the problem, have to replace:
__unsafe_unretained NSBlockOperation *weakOperation = operation;
with:
__block NSBlockOperation *weakOperation = operation;
BTW, for anyone interested there is a good video on concurrency, in particular drawing on a separate thread and using NSOperationQueue
's in WWDC2012 called Building Concurrent User Interfaces on IOS.
来源:https://stackoverflow.com/questions/14432029/how-to-cancel-nsoperationqueue