Checking if NSTimer was added to NSRunLoop

こ雲淡風輕ζ 提交于 2019-12-31 02:59:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!