在 NSApplicationMain 的文档中,它说:
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 [...].
“主线程”显然是指程序的第一个线程,其中 main(argc, argv)
启动。快速浏览 NSThread文档显示+ (BOOL)isMainThread
,它可用于确定当前线程是否是“主”线程。我运行了一些测试:无论 NSApplicationMain
是否已被调用,此方法都有效。
我的问题有两个(有些相关)部分:
NSApplicationMain
的主线程有什么特别之处?- Cocoa 首先是如何识别主线程的?
最佳答案
Here是通过重新实现函数来研究 NSApplicationMain 的好地方。 NSApplicationMain 必须从主线程调用,主要是因为
- 它处理主界面
- UI 元素(在多个系统中,不仅仅是 OS X)需要在同一个线程中调用才能正常运行。
- Cocoa 框架内提供的图形元素假设它们将在主线程中运行。
所以,由于 Cocoa 在主线程中调用事物,并且 UI 需要全部在同一个线程中运行,因此您需要在主线程中处理任何涉及 UI 的内容,包括 NSApplicationMain。
关于multithreading - 在Apple的Cocoa API中,为什么从主线程调用NSApplicationMain很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7425983/