Is there a way to avoid viewDidLoad beeing called

2019-02-27 16:37发布

问题:

i initialize tables, data etc in my main ViewController. For more settings, i want to call another Viewcontroller with:

 DateChangeController *theController = [self.storyboard instantiateViewControllerWithIdentifier:@"dateChangeController"];
[self presentViewController:theController animated:YES completion:^{NSLog(@"View controller presented.");}];

And some clicks later i return with a segue (custom:)

NSLog(@"Scroll to Ticket");
[self.sourceViewController presentModalViewController:self.destinationViewController animated:YES];

My Problem:

After returning to my main ViewController, viewDidLoad is called (everytime).I read, that the ARC releasing my mainView after "going" to the other ViewController and calling the viewDidUnload Method, but i want to keep all my data and tables i initialize at the beginning..

Any solution? Thank you very much!

回答1:

The problem is that you are doing this:

main view controller ->
    date change controller ->
        a *different* main view controller

In other words, although in your verbal description you use the words "returning to my main ViewController", you are not in fact returning; you are moving forward to yet another instance of this main view controller every time, piling up all these view controllers on top of one another.

The way to return to an existing view controller is not to make a segue but to return! The return from presentViewController is dismissViewController. You do not use a segue for that; you just call dismissViewController. (Okay, in iOS 6 you can in fact use a segue, but it is a very special and rather complicated kind of segue called an Unwind or Exit segue.)

If you do that, you'll be back at your old view controller, which was sitting there all along waiting for your return, and viewDidLoad will not be called.

So, this was a good question for you to ask, because the double call of viewDidLoad was a sign to you that your architecture was all wrong.



回答2:

I think you're taking the wrong approach - viewDidLoad is supposed to be called when it is called - it's a notification to you that the view is being refreshed or initially loaded. What you want to do is move that table initialization code somewhere else, or, at least, set a Boolean variable so that it is only called once. Would it work to create an object that has your table data when viewDidLoad is first called, then to check it to see if it's already been called?