2014-03-13 14 views
2

我試圖超時我的NSOperationNSTimer但我的計時器沒有被解僱。請參閱下面的代碼我寫在我的班級裏面,這是NSOperation無法使用NSTimer超時NSOperation

- (void)start { 
    // Start the timer for Time out before the ping activity starts 
    self.timeOutTriggerTimmer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(cancelTheOperation) userInfo:nil repeats:NO]; 
    [[NSRunLoop currentRunLoop] addTimer:self.timeOutTriggerTimmer forMode:NSDefaultRunLoopMode]; 

    // Check for cancellation 
    if ([self isCancelled]) { 
     [self completeOperation]; 
     return; 
    } 

    // Executing 
    [self willChangeValueForKey:@"isExecuting"]; 
    executing = YES; 
    [self didChangeValueForKey:@"isExecuting"]; 

    // Begin 
    [self beginOperation]; 
} 

回答

3

這是最簡單的只是計時器添加到主運行循環,而不是當前運行的循環:

[[NSRunLoop mainRunLoop] addTimer:self.timeOutTriggerTimmer forMode:NSDefaultRunLoopMode]; 

或者,你可以保持您的計時器,因爲它是(定於當前運行的循環),但你必須保持runloop活着,或許添加類似以下的start方法(注月底,蘋果公司建議這而非run法):

while ([self isExecuting] && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]); 

但是,這個方法(例如您設想的run方法)有效地保持了start方法的運行,直到執行完成爲止(使得似乎是併發操作的行爲更像是非併發操作)。

我懷疑你已經這樣做了,但爲了以防萬一,當你完成你的操作時確保你的計時器,否則定時器將保持該操作,直到定時器啓動,不必要地延遲了操作的釋放資源(並且即使可能已經完成操作,也調用cancelTheOperation)。

+0

接受這個答案,因爲它更有意義。謝謝@Rob。 – Abhinav

1

我發現了這個問題。我需要把下面的語句讓它執行。

[[NSRunLoop currentRunLoop] run]; 
+1

我會對這個解決方案保持警惕。請參閱[有關'run'方法的Apple文檔](https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/classes/nsrunloop_class/Reference/Reference.html#//apple_ref/doc/) uid/20000321-CHDEBABE)作爲首選替代方案。或者更簡單,只需使用主運行循環即可。如果你使用'run',做一些測試以確認'start'方法最終會終止。 – Rob