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];
}
Will the following cause a memory leak or could it be changed to be better somehow? With the countDownTimer = nil
being removed
-(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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以使用
scheduleTimer
方法的block
变体来避免循环引用。只需确保将
self
捕获为weak
变量即可。One can use
block
variant ofscheduleTimer
method to avoid retain cycles.Just make sure to capture
self
as aweak
variable.当 NSTimer 过期或失效时,它会自动减少其保留计数。没有必要将其设置为 nil,除非您已将其分配给保留的 ivar。 (在您的情况下,这意味着您还需要使用 self.countDownTimer 分配计时器
NSTimer automatically decrements its retain count when it expires or is invalidated. There is no need to set it equal to nil unless you have assigned it to an ivar that retains. (which in your case means you would have also needed to assign the timer using self.countDownTimer
我假设
countDownTimer
是一个 ivar?NSTimer
在存活时保留其目标,因此听起来您对[countDownTimer invalidate]
的调用正在释放对self
的最后一个引用并导致self
在-pauseTimer
方法中间释放。因此,任何对 self 的引用,甚至是隐式引用(例如访问 ivars)都会崩溃,或者至少会出现意外行为。谁在调用
-pauseTimer
?也许他们应该对您的对象有强烈的参考。I assume
countDownTimer
is an ivar?NSTimer
s retain their targets while they're alive, so it sounds like your call to[countDownTimer invalidate]
is releasing the last reference toself
and causingself
to deallocate in the middle of your-pauseTimer
method. As such, any reference toself
, even implicit references (e.g. accessing ivars) is going to crash, or at least behave unexpectedly.Who is calling
-pauseTimer
? Perhaps they should have a strong reference to your object.