检查NSTimer是否已添加到NSRunLoop

时间:2015-12-08 13:43:22

标签: objective-c cocoa nstimer 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];
}

有没有办法检查这个?

2 个答案:

答案 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];
}