开发者

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

开发者 https://www.devze.com 2023-04-04 19:28 出处:网络
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 functi开发者_J

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 functi开发者_JAVA技巧on 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消