[NSOperation cancelAllOperations]; 不会停止操作

Awe*_*ome 15 cocoa nsoperationqueue

xCode 4.4.1 OSX 10.8.2,看起来像[operation cancelAllOperations]; 不工作

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSOperationQueue *operation = [[NSOperationQueue alloc] init];
    [operation setMaxConcurrentOperationCount: 1];
    [operation addOperationWithBlock: ^{
        for (unsigned i=0; i < 10000000; i++) {
            printf("%i\n",i);
           }
    }];
    sleep(1);
    if ([operation operationCount] > 0) {
        [operation cancelAllOperations];
    }
}
Run Code Online (Sandbox Code Playgroud)

结果9999999

Car*_*zey 30

在您的块中,特别是在循环内部,请调用-isCancelled该操作.如果是真的,那就回来吧.

NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount: 1];

NSBlockOperation *operation = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakOperation = operation;
[operation addExecutionBlock: ^ {
    for (unsigned i=0; i < 10000000; i++) {
        if ([weakOperation isCancelled]) return;
        printf("%i\n",i);
    }
}];
[operationQueue addOperation:operation];

sleep(1);

if ([operationQueue operationCount] > 0) {
    [operationQueue cancelAllOperations];
}
Run Code Online (Sandbox Code Playgroud)

队列不能随意停止操作的执行 - 如果某些共享资源被从未被清理过的操作使用了怎么办?当知道被取消时,您有责任有序地结束操作.来自Apple的文档:

操作对象负责定期调用isCancelled并在方法返回YES时自行停止.

  • 值得注意的是,在ARC下,您必须对操作对象进行弱引用,并使用它来检查isCancelled,以避免保留周期. (4认同)