In the Apple Cocoa API, why is it important that the NSApplicationMain is called from the main thread?

The documentation for NSApplicationMain says:

Creates an application, downloads the main nib file from the main application package, and launches the application. You must call this function from the main thread of your application [...].

The "main thread" obviously refers to the first thread of the program where main(argc, argv) begins. A quick look at the NSThread documentation shows + (BOOL)isMainThread , which can be used to determine if the current thread is "main" or not. I conducted several tests: this method works regardless of whether there was another call to NSApplicationMain .

My question consists of two (several related) parts:

  • What is especially important in the main thread for NSApplicationMain ?
  • How does Cocoa identify the main thread first?
+7
source share
1 answer

Here is a good place to learn NSApplicationMain, following the reimplementation of the function. NSApplicationMain needs to be called from the main thread primarily because

  • It processes the main interface
  • User interface elements (on multiple systems, not just OS X) must be called on a single thread for proper operation.
  • The graphical elements provided by Cocoa suggest that they will work in the main thread.

So much, since Cocoa calls things in the main thread, and the user interface needs to be run on the same thread, you need to work in the main thread for anything related to the user interface, including NSApplicationMain.

+7
source

All Articles