在Apple的Cocoa API中,为什么从主线程调用NSApplicationMain很重要?
在 NSApplicationMain,它说:
创建应用程序,从应用程序的主包加载主 nib 文件,然后运行应用程序。您必须从应用程序的主线程调用此函数[...]。
“主线程”显然是指程序的第一个线程,从这里开始。快速浏览 NSThread 文档显示+ (BOOL)isMainThread
,它可用于确定当前线程是否是“主”线程。我运行了一些测试:无论 NSApplicationMain 是否已被调用,此方法都有效。
我的问题有两个(有些相关)部分:
- NSApplicationMain 的主线程有什么特别之处?
- Cocoa 首先是如何识别主线程的?
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:
- What is so special about the main thread for
NSApplicationMain
? - How does Cocoa identify the main thread in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里是通过重新实现函数来研究 NSApplicationMain 的好地方。 NSApplicationMain 必须从主线程调用,主要是因为
基本上,由于 Cocoa 在主线程中调用事物,并且 UI 需要全部在同一个线程中运行,因此您需要在主线程中处理任何涉及 UI 的内容,包括 NSApplicationMain。
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
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.