gpt4 book ai didi

cocoa - 如何创建只监听performSelector :onThread: and GUI events?的运行循环

转载 作者:行者123 更新时间:2023-12-03 17:32:54 25 4
gpt4 key购买 nike

我想创建一个单独的线程来运行自己的窗口。坦率地说,该文档对我来说没有意义。

所以我创建了一个带有 main 函数的 NSThread 。我启动线程,创建一个 NSAutoreleasePool,然后运行运行循环:

// Global:
BOOL shouldKeepRunning = YES;

- (void)threadMain {
NSAutoreleasePool *pool = [NSAutoreleasePool new];
// Load a nib file, set up its controllers etc.
while (shouldKeepRunning) {
NSAutoreleasePool *loopPool = [NSAutoreleasePool new];
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
[loopPool drain];
}
[pool drain];
}

但是由于没有注册端口或观察者,runUntilDate: 立即退出,CPU 利用率达到 100%。

所有线程通信都是通过调用performSelector:onThread:withObject:waitUntilDone:来处理的。显然,我没有正确使用 API。那么,我做错了什么?

最佳答案

AppKit 的大部分内容都不是线程安全的,并且在主线程之外操作时将无法正常工作 (1)。如果你试图忽视这一事实,你会发现只有痛苦和痛苦。

真正想要做什么需要为此窗口使用不同的线程?您只是想保持响应式用户界面吗?如果是这样,就有更多更好的方法来做到这一点。请参阅 NSOperation/NSOperationQueue (其中“工作单元”和“队列”是焦点,而不是“此窗口应在此线程上运行等”)。

我建议您重述您的问题,并清楚地说明您的具体目标。

(1) 对于某些类,需要付出大量的细心工作。对于其他人来说,它们是完全禁止的。

关于cocoa - 如何创建只监听performSelector :onThread: and GUI events?的运行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2632668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com