在Apple的Cocoa API中,为什么从主线程调用NSApplicationMain很重要?

发布于 2024-12-05 05:12:57 字数 759 浏览 1 评论 0原文

NSApplicationMain,它说:

创建应用程序,从应用程序的主包加​​载主 nib 文件,然后运行应用程序。您必须从应用程序的主线程调用此函数[...]。

“主线程”显然是指程序的第一个线程,从这里开始。快速浏览 NSThread 文档显示+ (BOOL)isMainThread,它可用于确定当前线程是否是“主”线程。我运行了一些测试:无论 NSApplicationMain 是否已被调用,此方法都有效。

我的问题有两个(有些相关)部分:

  1. NSApplicationMain 的主线程有什么特别之处?
  2. 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:

  1. What is so special about the main thread for NSApplicationMain?
  2. How does Cocoa identify the main thread in the first place?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

茶花眉 2024-12-12 05:12:57

这里是通过重新实现函数来研究 NSApplicationMain 的好地方。 NSApplicationMain 必须从主线程调用,主要是因为

  1. 它处理主界面
  2. UI 元素(在多个系统中,而不仅仅是 OS X),需要在同一线程中调用才能正常运行。
  3. Cocoa 框架内提供的图形元素假设它们将在主线程中运行。

基本上,由于 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

  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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文