假如有一個需求,要求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; } }