检查 NSTimer 是否被添加到 NSRunLoop
Checking if NSTimer was added to NSRunLoop
假设我在代码中的某个地方创建了 NSTimer,稍后我想将它添加到 mainRunLoop 中,前提是之前还没有添加它:
NSTimer* myTimer = [NSTimer timerWithTimeInterval:1.0f
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
代码中的另一个地方:
if("my myTimer wasn't added to the mainRunLoop")
{
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
[runLoop addTimer:myTimer forMode:NSDefaultRunLoopMode];
}
有没有办法检查这个?
是;在实例变量中保留对它的引用并检查非 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];
}
试试这个:
CFRunLoopRef loopRef = [[NSRunLoop mainRunLoop] getCFRunLoop];
BOOL timerAdded = CFRunLoopContainsTimer(loopRef, (CFRunLoopTimerRef)myTimer ,kCFRunLoopDefaultMode);
然后检查 timerAdded
变量
假设我在代码中的某个地方创建了 NSTimer,稍后我想将它添加到 mainRunLoop 中,前提是之前还没有添加它:
NSTimer* myTimer = [NSTimer timerWithTimeInterval:1.0f
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
代码中的另一个地方:
if("my myTimer wasn't added to the mainRunLoop")
{
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
[runLoop addTimer:myTimer forMode:NSDefaultRunLoopMode];
}
有没有办法检查这个?
是;在实例变量中保留对它的引用并检查非 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];
}
试试这个:
CFRunLoopRef loopRef = [[NSRunLoop mainRunLoop] getCFRunLoop];
BOOL timerAdded = CFRunLoopContainsTimer(loopRef, (CFRunLoopTimerRef)myTimer ,kCFRunLoopDefaultMode);
然后检查 timerAdded
变量