how to cancel out of operation created with addOperationWithBlock?

北城余情 提交于 2019-11-28 23:16:49

A better solution might be to use NSBlockOperation and add that to the queue instead of a raw block. You could do something like:

__block NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
  while(![operation isCancelled]){
    //Some long operation
  }
}];

[[self queue] addOperation:operation];

This lets you use blocks while giving you a little more control over the operation... and a few more NSOperation niceties as well (like the ability to add completion blocks, for example).

You can't really check to see if you need to cancel the operation if it's in a block. If it's in a block and it's supposed to be canceled then it is canceled. Accessing NSOperation properties is not possible because the block is not an NSOperation instance per se.

Example code:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSOperationQueue *q = [[NSOperationQueue alloc] init];
    [q addOperationWithBlock:^{
        [NSThread sleepForTimeInterval:10];
        NSLog(@"Block 1");
    }];
    [q addOperationWithBlock:^{
        [NSThread sleepForTimeInterval:3];
        NSLog(@"Block 2");
    }];
    [q cancelAllOperations];
    [NSThread sleepForTimeInterval:15];

    [pool drain];
    return 0;
}

If you remove the cancelAllOperations call then the blocks fire as you would expect.

I would suggest that if you need to have finer grained control over the operation's cancel state and interplay with the NSOperationQueue that you would be better off using an NSOperation rather than an NSBlockOperation. You can subclass NSOperation to accomplish this.

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