问题
Let's say I'm creating NSTimer in some place in the code and later, I want to add it to the mainRunLoop only if it wasn't already added before:
NSTimer* myTimer = [NSTimer timerWithTimeInterval:1.0f
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
Another place in the code:
if("my myTimer wasn't added to the mainRunLoop")
{
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
[runLoop addTimer:myTimer forMode:NSDefaultRunLoopMode];
}
Is there a way to check this?
回答1:
Try this:
CFRunLoopRef loopRef = [[NSRunLoop mainRunLoop] getCFRunLoop];
BOOL timerAdded = CFRunLoopContainsTimer(loopRef, (CFRunLoopTimerRef)myTimer ,kCFRunLoopDefaultMode);
then check timerAdded
variable
回答2:
Yes; keep a reference to it in an instance variable and check for non-nil
:
@interface MyClass() {
NSTimer *_myTimer;
}
@end
...
if (!_myTimer)
{
_myTimer = [NSTimer timerWithTimeInterval:1.0f
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
[runLoop addTimer:_myTimer forMode:NSDefaultRunLoopMode];
}
来源:https://stackoverflow.com/questions/34157455/checking-if-nstimer-was-added-to-nsrunloop