Reputation: 1835
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
Reputation: 21808
Try this:
CFRunLoopRef loopRef = [[NSRunLoop mainRunLoop] getCFRunLoop];
BOOL timerAdded = CFRunLoopContainsTimer(loopRef, (CFRunLoopTimerRef)myTimer ,kCFRunLoopDefaultMode);
then check timerAdded
variable
Upvotes: 3
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