ios - NSTimer 内存泄漏?

标签 ios objective-c xcode nstimer

以下是否会导致内存泄漏或是否可以通过某种方式将其更改为更好?随着 countDownTimer = nil 被移除

-(void)viewDidLoad{    
  countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(loadNewTime:) userInfo:nil repeats:YES];
}

-(void)pauseTimer{            
   NSLog(@"Fired");
   [countDownTimer invalidate];
   //countDownTimer = nil <------ Causes crash when run
}

-(void)resumeTimer{
   countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(loadNewTime:) userInfo:nil repeats:YES];
}

最佳答案

可以使用 scheduleTimer 方法的 block 变体来避免保留循环。

var timer = Timer()

func startTimer() {
  timer = Timer.scheduleTimer(withTimerInterval: 1.0, repeats: true, block: { [weak self] (timer) in
     self?.performUpdate(timer: timer)
  })
}

func stopTimer() {
   timer.invalidate()
}

只需确保将 self 捕获为 weak 变量即可。

关于ios - NSTimer 内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7826394/

相关文章:

iphone - 多 View 应用程序在模拟器中显示空白屏幕

ios - 无法关闭模态视图 Controller

ios - 用户界面图像 : How to get website tab icon

javascript - 尝试使用 highcharts 将数据点注入(inject) iOS webView

ios - NSNotification 与 UITextFieldDelegate

iphone - 如何使用MPMoviePlayerViewController播放youtube视频

ios - 在表中显示单元格创建时间 (Swift)

iphone - TableView 被标题栏遮挡

objective-c - UIImageView 的交互性

Ios-deploy 安装不起作用 - macOS High Sierra (10.13.5)