[NSOperation cancelAllOperations];不会停止操作

时间:2012-09-30 10:58:58

标签: 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];
    }
}

结果9999999

1 个答案:

答案 0 :(得分:29)

在您的块中,特别是在循环内部,在操作上调用-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];
}

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

  

操作对象负责调用isCancelled   如果方法返回YES,则定期并自行停止。