假设我在代码中的某个位置创建了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];
}
有没有办法检查这个?
答案 0 :(得分:3)
试试这个:
CFRunLoopRef loopRef = [[NSRunLoop mainRunLoop] getCFRunLoop];
BOOL timerAdded = CFRunLoopContainsTimer(loopRef, (CFRunLoopTimerRef)myTimer ,kCFRunLoopDefaultMode);
然后检查timerAdded
变量
答案 1 :(得分:2)
是;在实例变量中保留对它的引用,并检查非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];
}