美文网首页
NSTimer 导致UIViewController无法正常释放

NSTimer 导致UIViewController无法正常释放

作者: 赵哥窟 | 来源:发表于2018-11-13 11:33 被阅读14次

假如有一个需求,要求B页面每隔5秒请求一次数据,所以用了NSTimer

代码如下

 self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateMonitorTime) userInfo:nil repeats:YES];
 [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];

- (void)updateMonitorTime
{
    NSLog("请求数据");
}

当回到A页面的时候发现还在B页面继续调用接口。

原因:当我们使用NSTimer的方法时,定时器对象会对它的target(即self:当前控制器)持有强引用,如果定时器不销毁,则控制器无法释放。

解决办法:

- (void)viewWillDisappear:(BOOL)animated
{
    if (self.timer != nil) {
         [self.timer invalidate];
         self.timer = nil;
    }
}

相关文章

网友评论

      本文标题:NSTimer 导致UIViewController无法正常释放

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