0

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:

  1. Add a view controller as a child VC. The parent is registered as the child's delegate.
  2. The child calls delegate method to call some API.
  3. The parent gets response JSON data on the main queue.
  4. 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.

funct7
  • 3,407
  • 2
  • 27
  • 33

1 Answers1

0

The problem is not that your View Controller is outliving the View but its the fact that once a Queue i.e. a closure or a block (In your case the callback of your API calling method) is dispatched the system keeps it alive and keeps a strong reference to it even when the owner of the closure or block (In your case your View Controller) is deallocated. So for the solution you can use weak self in your closure or block.

nishith Singh
  • 2,968
  • 1
  • 15
  • 25
  • 1. The owner of the closure is the networking object, not the view controller. I saw it happen once under my watch. The presenting view controller was alive. – funct7 Nov 04 '16 at 07:11
  • If you can post some code it will help better understand your problem – nishith Singh Nov 04 '16 at 07:14
  • @nishithSingh is right, try to keep a weak reference of closure in the networking object. And if you can't share the code then this is probably the most one can help you. – Adeel Miraj Nov 04 '16 at 08:20