How to cancel NSOperationQueue

橙三吉。 提交于 2019-12-06 07:08:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!