Roi Mulia Roi Mulia - 10 months ago 31
Swift Question

Reuse UIViewController instance across theards

This is our scenario,we have VC A,B and C. As well, we have VC X.

I need to use & present VC X within A,B and C.

I don't want to re-create an instance every time i'm on each VC.
So basically i was thinking on creating global instance/property at the

App Delegate
and initialize it there,and just present VC X when needed.

vcX = self.storyboard?.instantiateViewControllerWithIdentifier("IAP") as! newIAPClass

Does this could cause unexpected behavior?


Here are some thoughts on reusing a single copy of a viewController X:

  1. Thread safety should have nothing to do with it as all user interface interactions need to be performed on the main thread.

  2. Each instance of a viewController can only have at most one parent at a time. So as long as you only use X once in your view hierarchy, you should be OK. For example A presents B which presents X, and then X returns to B which returns to A. Then A presents C which presents X. This would work fine since X only has one parent at any given time.

  3. Doing this would mean that X would retain all of its settings between presentations, so it would be the responsibility of the presenter to clean it up and properly initialize it before presentation. By keeping a permanent global copy of X around, it will retain all of the data it has between calls. For example, if there is an input text field, that text field will still contain the text from a previous use. The presenter will be responsible for reinitializing any data that viewController X retains and uses. This would include a delegate pointer.

An example of a scenario that would cause problems: A, B, and C are all contained in a UITabBarController. Each one can present X so that the user can change settings. This will fail if A presents X and then the user switches tabs to B and then presents X again because now X will have both A and B as parents, which can't work.