View controller getting duplicate instantiation

2019-02-26 05:06发布

This should be pretty straight forward.

When I use the navigation controller to segue from my root view to my 2nd view, the 2nd view loads fine. The 2nd view creates a timer in "viewDidLoad" to call a method "updateData" periodically.

Maybe I'm not understanding the system here, but when I go back to root and forward again to the 2nd view, I'm getting a completely new instance of the 2nd view controller, which makes a new timer (updateData is getting called twice as frequently).

This is not correct default behavior is it? How can I show the first instance of the 2nd view controller instead of creating a new one?

2条回答
疯言疯语
2楼-- · 2019-02-26 05:11

Off the top of my head: In your second view controllers deallocate method, you should stop the timer of the "updateData", as it is not properly deallocated. Try that!

[self.timer invalidate];
查看更多
beautiful°
3楼-- · 2019-02-26 05:28

It's not necessarily true that persistent objects shouldn't be properties of view controller. You can create a property for your second controller (in the root view controller), and only instantiate it the first time you push it. Because you have a strong pointer to it, it won't be deallocated when you go back to the first controller, and your timer will continue to operate.

- (IBAction)goToSecondView {
    if (!self.secondViewController) { // secondViewController is a strong property
        self.secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"Second"]; 
    }
    [self.navigationController pushViewController:self.secondViewController animated:YES];
}
查看更多
登录 后发表回答