2012-09-30 54 views
15

xCode 4.4.1 OSX 10.8.2,看起來像[operation cancelAllOperations];不工作[NSOperation 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

回答

26

你的塊中,特別是在循環內,調用-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。

+0

所以沒有辦法停止操作,直到它完成? – Awesome

+0

有 - 在代碼中,你檢查isCancelled。如果這是真的,那麼你停止執行。操作自行停止,隊列只是告訴它取消。那有意義嗎? –

+0

謝謝你:)我不明白。 – Awesome