问题描述
这应该很简单.
当我使用导航控制器从根视图切换到第二视图时,第二视图会很好地加载.第二个视图在"viewDidLoad"中创建一个计时器,以定期调用方法"updateData".
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.
也许我在这里不了解系统,但是当我回到root并再次转到第二个视图时,我得到了一个第二个视图控制器的全新实例,该实例创建了一个新计时器(updateData是被打两次).
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?
推荐答案
持久对象不应该是视图控制器的属性并不一定是正确的.您可以为第二个控制器(在根视图控制器中)创建一个属性,并且仅在第一次按下它时实例化它.因为您有很强的指向性,所以当您返回第一个控制器时,它不会被释放,并且您的计时器将继续运行.
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];
}
这篇关于视图控制器获取重复的实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!