0
我使用下面的代碼來消除選擇器saveCurrentDocument的執行。在後臺線程中調用它時,無法使NSTimer無效
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if (debounceTimer != NULL) {
[debounceTimer invalidate];
debounceTimer = NULL;
}
debounceTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(saveCurrentDocument) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:debounceTimer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});
目前,我注意到,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)正在創造另一個線程每次一個用戶在該應用程序的信,所以我試圖把它改成這樣:
if (debounceQueue == nil) {
debounceQueue = dispatch_queue_create("com.testing.SaveQueue", NULL);
}
dispatch_async(debounceQueue, ^{
if (debounceTimer != NULL) {
[debounceTimer invalidate];
debounceTimer = NULL;
}
debounceTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(saveCurrentDocument) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:debounceTimer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});
但現在[debounceTimer invalidate]不再有效,每次都調用saveCurrentDocument。
任何人都可以向我解釋爲什麼會發生這種情況嗎?
感謝您注意到,在此修復。但我仍然有同樣的問題,在dispatch_queue_create上使用DISPATCH_QUEUE_SERIAL時無效無效 –
這可能有所幫助:http://stackoverflow.com/questions/10522928/run-repeating-nstimer-with-gcd – mikepj