In the app I'm working on, we sometimes get random crashes in the completion part of a network request.
The chain of events is as follows:
- Add a view controller as a child VC. The parent is registered as the child's delegate.
- The child calls delegate method to call some API.
- The parent gets response JSON data on the main queue.
- The parent updates views in the child according to the received data as completion.
In the last part, however, crashes happen randomly. It's pretty hard to reproduce, and Crashlytics shows the crash happens due to referencing a nil variable, a subview in the child view controller's view hierarchy. The parent is alive at this point.
Instead of crashing upon calling a function of the child view controller, it crashes when referencing the view inside the function, so my only guess is that the view is released before the child view controller is.
So my question is, as the title says, is it possible or expected that the view controller outlives its view?
This is what is says in the UIViewController
document:
A view controller is the sole owner of its view and any subviews it creates. It is responsible for creating those views and for relinquishing ownership of them at the appropriate times such as when the view controller itself is released.
I always thought the view is released as a result of the view controller's reference count being 0.
UPDATE Instead of presenting, I'm adding it as a child view controller. Added a more detailed explanation of what happens.