Checking if NSTimer was added to NSRunLoop

前端 未结 2 1764
后悔当初
后悔当初 2021-01-22 09:37

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* myTim         


        
相关标签:
2条回答
  • 2021-01-22 09:56

    Try this:

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

    then check timerAdded variable

    0 讨论(0)
  • 2021-01-22 09:57

    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];
    }
    
    0 讨论(0)
提交回复
热议问题