Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In the documentation for NSApplicationMain, it says:

Creates the application, loads the main nib file from the application’s main bundle, and runs 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) starts. A quick look through the NSThread documentation reveals + (BOOL)isMainThread, which can be used to determine whether the current thread is the "main" one or not. I ran some tests: this method works regardless of whether NSApplicationMain has been called yet.

My question has two (somewhat related) parts:

  1. What is so special about the main thread for NSApplicationMain?
  2. How does Cocoa identify the main thread in the first place?
like image 938
Calvin Avatar asked Sep 15 '11 04:09

Calvin


1 Answers

Here is a good place to study NSApplicationMain by following a re-implementation of the function. NSApplicationMain must be called from the main thread primarily because

  1. It handles the primary interface
  2. UI elements (in several systems, not just OS X) need to all be called within the same thread to function correctly.
  3. Graphical elements provided within the Cocoa framework assume they'll be running in the main thread.

So pretty much, since Cocoa calls things in the main thread, and the UI needs to all be run in the same thread, you need to work within main thread for anything touching UI, including NSApplicationMain.

like image 180
matthias Avatar answered Oct 14 '22 06:10

matthias