开发者

Where to invalidate NSTimer in view lifecycle?

I have a weird problem invalidating NSTimer. As long as the user is on a particular screen, I need to constantly update it. I'm using NSTimer to accomplish it. I wrote the below piece of code in viewDidLoad method.

- (void)viewDidLoad {
self.pollServerForUpdates = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(fetchNewDataFromServer:)
userInfo:nil
repeats:YES];
}

Problem is when I try to invalidate the timer. As I want the app to stop polling the server when the user leaves the screen, I put the timer invalidation code in viewWillDisappear method.

-(void) viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:YES];
//NSLog(@"%d",[self.view retainCount]);
[self.pollServerForUpdates invalidate];
self.pollServerForUpdates = nil;
}

I use a navigation controller to go back and forth between my main view and the polling view. The app crashes if I move between my main view and polling view real fast. I enabled the NSZombie to see whats happening and this is what I get

 *** -[CALayer retainCount]: message sent to deallocated instance 0x1c3be0

If I remove the ti开发者_运维知识库mer invalidation my app works fine. But I want to stop the polling (timer) as soon as the user leaves the screen.

I believe this is happening because the timer is called a split second before the view is released, how do I avoid it? Do I need to change my design? Any help will be appreciated.

p.s: I can't use push notifications on this screen.


It may be that the bug is somewhere else, with some other class that is using your view without holding a reference to it. If you don't invalidate your timer than it will have a reference to your view forever, potentially extending its lifespan and masking memory management bugs elsewhere in your code.

Try breaking on exceptions, and see where the call to the zombie is coming from.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜