I have a navigation controller. One of the views adds custom subviews in its viewDidAppear:
. I notice that the first time I navigate to an instance of this view controller after launching the app, viewDidAppear:
invokes twice. If I pop this view off the stack and navigate to it again, viewDidAppear:
invokes only once per appearance. All subsequent appearances invoke viewDidAppear:
once.
The problem for me is that the first time I get to this view I end up with twice the number of subviews. I work around this problem by introducing a flag variable or some such, but I'd like to understand what is happening and how come I get two invocations in these circumstances.
You should never rely on -viewWillAppear:
/-viewDidAppear:
being called appropriately balanced with the disappear variants. While the system view controllers will do the best they can to always bracket the calls properly, I don't know if they ever guarantee it, and certainly when using custom view controllers you can find situations where these can be called multiple times.
In short, your -viewWillAppear:
/-viewDidAppear:
methods should be idempotent, meaning if -viewDidAppear:
is called twice in a row on your controller, it should behave properly. If you want to load custom views, you may want to do that in -viewDidLoad
instead and then simply put the on-screen (if they aren't already) in -viewDidAppear:
.
You could also put a breakpoint in your -viewDidAppear:
method to see why it's being called twice the first time it shows up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With