NSRunLoop methods should only be accessed on it's corresponding thread.

This commit is contained in:
Michael Kirk 2019-01-17 11:00:08 -07:00 committed by Matthew Chen
parent 64cdaae02e
commit 323249baa0
3 changed files with 17 additions and 43 deletions

View File

@ -14,12 +14,6 @@ NS_ASSUME_NONNULL_BEGIN
userInfo:(nullable id)userInfo
repeats:(BOOL)repeats;
+ (NSTimer *)weakTimerWithTimeInterval:(NSTimeInterval)timeInterval
target:(id)target
selector:(SEL)selector
userInfo:(nullable id)userInfo
repeats:(BOOL)repeats;
@end
NS_ASSUME_NONNULL_END

View File

@ -64,24 +64,6 @@ static void *kNSTimer_OWS_Proxy = &kNSTimer_OWS_Proxy;
return timer;
}
+ (NSTimer *)weakTimerWithTimeInterval:(NSTimeInterval)timeInterval
target:(id)target
selector:(SEL)selector
userInfo:(nullable id)userInfo
repeats:(BOOL)repeats
{
NSTimerProxy *proxy = [NSTimerProxy new];
proxy.target = target;
proxy.selector = selector;
NSTimer *timer = [NSTimer timerWithTimeInterval:timeInterval
target:proxy
selector:@selector(timerFired:)
userInfo:userInfo
repeats:repeats];
[timer ows_setProxy:proxy];
return timer;
}
@end
NS_ASSUME_NONNULL_END

View File

@ -192,25 +192,23 @@ NSString *const OWSOperationKeyIsFinished = @"isFinished";
self.remainingRetries--;
dispatch_sync(self.retryTimerSerialQueue, ^{
OWSAssertDebug(self.retryTimer == nil);
[self.retryTimer invalidate];
NSTimer *retryTimer = [NSTimer weakTimerWithTimeInterval:self.retryInterval
target:self
selector:@selector(runAnyQueuedRetry)
userInfo:nil
repeats:NO];
self.retryTimer = retryTimer;
// The `scheduledTimerWith*` methods add the timer to the current thread's RunLoop.
// Since Operations typically run on a background thread, that would mean the background
// thread's RunLoop. However, the OS can spin down background threads if there's no work
// being done, so we run the risk of the timer's RunLoop being deallocated before it's
// fired.
//
// To ensure the timer's thread sticks around, we schedule it on the main RunLoop.
[NSRunLoop.mainRunLoop addTimer:retryTimer forMode:NSDefaultRunLoopMode];
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_sync(self.retryTimerSerialQueue, ^{
OWSAssertDebug(self.retryTimer == nil);
[self.retryTimer invalidate];
// The `scheduledTimerWith*` methods add the timer to the current thread's RunLoop.
// Since Operations typically run on a background thread, that would mean the background
// thread's RunLoop. However, the OS can spin down background threads if there's no work
// being done, so we run the risk of the timer's RunLoop being deallocated before it's
// fired.
//
// To ensure the timer's thread sticks around, we schedule it while on the main RunLoop.
self.retryTimer = [NSTimer weakScheduledTimerWithTimeInterval:self.retryInterval
target:self
selector:@selector(runAnyQueuedRetry)
userInfo:nil
repeats:NO];
});
});
}