I use the code below to debounce the execution of the selector saveCurrentDocument.
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];
});
Currently, I noticed that dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) is creating another thread everytime an user types a letter in the app, so I tried to change it to this:
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];
});
But now [debounceTimer invalidate] doesn't work anymore, and it's calling saveCurrentDocument every time.
Can anyone explain to me why this is happening?