2011-03-07 19 views
6

從文檔:iOS - 如何檢查NSOperation是否在NSOperationQueue中?

的操作對象可以是在一個時間至多一個操作隊列,並且如果該操作已在另一個隊列此方法將引發NSInvalidArgumentException異常。同樣,如果操作當前正在執行或已經完成執行,此方法將引發NSInvalidArgumentException異常。

那麼如何檢查我是否可以安全地將NSOperation添加到隊列中?

我知道的唯一方法是添加操作,然後嘗試捕獲異常,如果操作已經在隊列中或之前執行。

回答

14

NSOperationQueue對象有一個名爲operations的屬性。

如果你有一個引用你的隊列,很容易檢查。

可以檢查作業的NSArray的包含您NSOperation這樣的:

NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

NSOperation *operation = [[NSOperation alloc] init]; 

[queue addOperation:operation]; 

if([queue operations] containsObject:operation]) 
    NSLog(@"Operation is in the queue"); 
else 
    NSLog(@"Operation is not in the queue"); 

或者你可以在所有的對象迭代:

for(NSOperation *op in [queue operations]) 
    if (op==operation) { 
     NSLog(@"Operation is in the queue"); 
    } 
    else { 
     NSLog(@"Operation is not in the queue"); 
    } 

告訴我,如果這是你在找什麼對於。

或者,NSOperation對象有幾個屬性可以讓你檢查它們的狀態;如:isExecutingisFinishedisCancelled,等...

+0

但如果我有多個操作隊列會發生什麼?我應該檢查每個操作隊列嗎?我可以做到這一點,但這是最好的辦法嗎? – 2011-03-07 08:54:22

+1

@ xlc0212:我能想到的另一個解決方案是子類NSOperation,它實際上受到了Apple的鼓勵;並添加一個布爾屬性「isInQueue」,並將其添加到隊列中時標記爲YES。像這樣,您只需在將操作添加到隊列之前檢查此屬性。 – Zebs 2011-03-07 09:08:21

+0

我應該何時標記操作?我應該在將它添加到隊列中之前手動設置它,還是應該重寫將由隊列調用的一些方法,然後設置標誌 – 2011-03-07 09:31:35

4

當您添加一個的NSOperation對象到NSOperationQueue,在NSOperationQueue保留的對象,所以的NSOperation的創建者可以釋放。如果你保持這種策略,NSOperationQueues將始終是它們的唯一所有者NSOperation對象,因此您將無法將對象添加到其他任何隊列中的NSOperation對象。

如果你還是想引用單個的NSOperation對象後,他們已經加入到隊列中,你可以這樣做使用NSOperationQueue- (NSArray *)operations方法。

相關問題