I have a UIViewController class with a variable shared that allows other classes to reach it as a singleton. However, the compiler (with Main Thread Checker enabled in Scheme Settings) is flagging the variable in purple with the warning:
-[UIViewController init] must be used from main thread only
I was not aware that merely including a shared variable to initiate the View Controller as a singleton is not allowed. I guess it makes sense insofar as when you initiate the VC it initiates the life cycle and views. But would appreciate someone confirming this and/or further shedding light on what is going on.
Here is the code that triggers the warning:
@objcMembers class MyVC : UIViewController, UITableViewDelegate, UITableViewDataSource,UITextViewDelegate {
static var shared = MyVC()
}
UIViewControllersingleton is definitely not a pattern I would be following. While a "root" view controller may indeed be in the view controller hierarchy for the lifetime of your app, it is still probably better to obtain the reference dynamically via, say, therootViewControllerproperty of your window or scene, than to use a singleton. Your question also implies that you are using a view controller where a data model would be more appropriate.MyVC.sharedis occurring from a non-main queue context. Since any operation that actually resulted in the view controller being added to the view hierarchy would have to be on the main queue, this would also indicate thatMyVC.sharedis not actually in the view hierarchy. You should be using one of the designated initialisers for aUIViewController, notinit()Window, but now you should access the current window scene. Singletons make testing harder and lead to undesirable class coupling. I say that they can be useful and, yes, in some cases I will still use them, but I try not to. And a singletonUIViewControlleris definitely a bad idea.