Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to create a UIViewController on a background thread?

Related: Is it ok to create a UIView on a background thread?

Is this background-thread code safe?

let viewController = MyViewController(nibName: nil, bundle: nil)
viewController.title = "My Title"
viewController.myProperty = true
dispatch_async(dispatch_get_main_queue(), {
    self.navigationController?.pushViewController(viewController, animated: true)
})
like image 628
ma11hew28 Avatar asked Nov 03 '15 23:11

ma11hew28


2 Answers

It seems that @ozgur answer is out of date now. If you try and create a UIViewController from a background thread in the latest version of Xcode (Version 11.5 at the time of writing) then you will get the following error:

-[UIViewController init] must be used from main thread only
like image 106
pls Avatar answered Sep 20 '22 14:09

pls


It depends on what the instance variables are actually doing. General rule is that the code running by a background thread should not trigger any UI updates such as view.addSubview(..) or view.setNeedsLayout etc, then it is safe to play around with a view controller using a background thread.

Another example would be navigation controllers. For instance, once a view controller was pushed onto a navigation stack, even updating viewController.title can be dangerous so you should make sure viewController.myProperty = true doesn't trigger any UI updates. Personally, I would do the following assignments in the main thread to feel safe:

dispatch_async(dispatch_get_main_queue(), {
  viewController.title = "My Title"
  viewController.myProperty = true
  ...
})

Long story short, you can initialize new UIView or UIViewController (or any UIResponder) in a background thread however, you should be changing any of its properties triggering UI updates within main thread. So create in background but update in main thread.

like image 31
Ozgur Vatansever Avatar answered Sep 21 '22 14:09

Ozgur Vatansever