美文网首页
iOS 定时器NSTimer循环引用问题解决

iOS 定时器NSTimer循环引用问题解决

作者: 朝辉 | 来源:发表于2019-04-29 11:44 被阅读0次
    通常在使用NSTimer时是如下:

    这样self强引用timer,timer强引用self,会造成self和timer循环引用,self和timer都销毁不了。

    //需要主动开启timer
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self 
    selector:@selector(loopTimer:) userInfo:nil repeats:YES];
    self.timer = timer;
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:timer forMode:NSRunLoopCommonModes];
    [runLoop run];
    
    //自动开启timer
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self 
    selector:@selector(loopTimer:) userInfo:nil repeats:YES];
    self.timer = timer;
    
    //定时器回调
    - (void)loopTimer:(NSTimer *)timer{
    //执行任务
    }
    

    解决方案:使用isLoop变量记录状态,在需要销毁定时器的时候把isLoop赋值为NO。

    //需要主动开启timer
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self 
    selector:@selector(loopTimer:) userInfo:nil repeats:YES];
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:timer forMode:NSRunLoopCommonModes];
    [runLoop run];
    self.isLoop = YES;
    
    //自动开启timer
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self 
    selector:@selector(loopTimer:) userInfo:nil repeats:YES];
    self.isLoop = YES;
    
    //定时器回调
    - (void)loopTimer:(NSTimer *)timer{
      if(self.isLoop = YES){
       //执行任务
      }else{
        //停止timer 并销毁
        [timer invalidate];
        timer = nil;
      }
    }
    

    相关文章

      网友评论

          本文标题:iOS 定时器NSTimer循环引用问题解决

          本文链接:https://www.haomeiwen.com/subject/spzenqtx.html