NSTimer does not invalidate

2019-03-01 12:01发布

问题:

I have a problem invalidating my timer.

@property (nonatomic, strong) NSTimer *timer;

Inside my block on success, I am allocating and setting my timer on main thread:

dispatch_async(dispatch_get_main_queue(), ^{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:[Config refreshInterval].integerValue target:self selector:@selector(methodThatHasABlockCalledMentionedAbove) userInfo:nil repeats:NO];
});

At my textFieldDidBeginEditing I am invalidating my timer like this:

dispatch_async(dispatch_get_main_queue(), ^{
        [self.timer invalidate];
        self.timer = nil;
 });

My method still gets executed on timer. What's the catch?

回答1:

Maybe you are setting several timer objects without invalidating the old ones first?!

releasing a timer objects thats already scheduled will not invalidate the timer, so:

before you do self.timer = .... , call [self.timer invalidate];