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()
}
Your question is making the assumption that you are getting a compiler warning due to the use of a singleton view controller. This is not the case.
The warning about calling UIViewController init
on a non-main queue is actually a runtime warning. Note that the scheme setting "Main Thread Checker" is under the "Runtime API Checking" section of the Diagnostics tab. Note that compiler warning show in Xcode as yellow triangles. Runtime warnings, such as this, appear as purple triangles.
The warning is not due to the code you posted. It is due to some other code that is making the first call to MyVC.shared
from a non-main queue. The solution is to find the offending code and ensure, like all UI code, that it is only called from the main queue.
Put a breakpoint on the line static var shared = MyVC()
and run your app to see which code calls it first. You should see from the stack trace shown at that point that it is on something other than Thread 0.