Sanich
Sanich

Reputation: 1835

Checking if NSTimer was added to NSRunLoop

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?

Upvotes: 2

Views: 438

Answers (2)

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

Try this:

CFRunLoopRef loopRef = [[NSRunLoop mainRunLoop] getCFRunLoop];
BOOL timerAdded = CFRunLoopContainsTimer(loopRef, (CFRunLoopTimerRef)myTimer ,kCFRunLoopDefaultMode);

then check timerAdded variable

Upvotes: 3

trojanfoe
trojanfoe

Reputation: 122391

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

Upvotes: 2

Related Questions