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

通常在使用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循环引用问题解决)