【发布时间】:2010-12-07 23:17:14
【问题描述】:
我有一个没有 GUI 的多 posix 线程 Linux C++ 应用程序,我希望能够在其中偶尔使用 Cocoa 控件,即文件上传/下载对话框和警报。
我远非 Cocoa 专家,但能够构建一些按预期工作的 Objective-C++ 测试/演示应用程序。
现在我已将 Cocoa 代码集成到我的应用程序中,我似乎无法将内容发布到主 GUI 线程。也许我没有做我需要做的事情来创建一个,我真的不确定。这是我的 .mm 文件中的内容:
#ifdef MACOS
@interface CocoaInterface : NSObject
{
}
- (id) init;
- (void) ShowFileUploadDialog;
- (void) ShowFileDownloadDialog;
@end
@implementation CocoaInterface
- (id) init
{
cout << "Creating NSAutoreleasePool" << endl;
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
cout << "Creating NSApplication" << endl;
NSApplication* app = [[NSApplication alloc] init];
cout << "Calling NSApplication::finishLaunching" << endl;
[app finishLaunching];
[super init];
return self;
}
- (void) ShowFileUploadDialog
{
cout << "Entering ShowFileUploadDialog" << endl;
if ([NSThread isMainThread])
{
// Show file dialog
cout << "Calling NSRunAlertPanel" << endl;
NSRunAlertPanel(@"This is a test", @"Does it work?", @"Yes", @"No", @"");
}
else
{
//NSRunAlertPanel(@"This is a test", @"Does it work?", @"Yes", @"No", @"");
cout << "Redirecting ShowFileUploadDialog call to main thread." << endl;
[self performSelectorOnMainThread:@selector(ShowFileUploadDialog) withObject:nil waitUntilDone:YES];
}
}
- (void) ShowFileDownloadDialog
{
cout << "Entering ShowFileDownloadDialog" << endl;
if ([NSThread isMainThread])
{
// Show file dialog
cout << "Calling NSRunAlertPanel" << endl;
NSRunAlertPanel(@"This is a test", @"Does it work?", @"Yes", @"No", @"");
}
else
{
//NSRunAlertPanel(@"This is a test", @"Does it work?", @"Yes", @"No", @"");
cout << "Redirecting ShowFileDownloadDialog call to main thread." << endl;
[self performSelectorOnMainThread:@selector(ShowFileDownloadDialog) withObject:nil waitUntilDone:YES];
}
}
@end
#endif
我从处理传入网络消息的各个线程中的代码中调用它:
cout << "Creating CocoaInterface." << endl;
CocoaInterface* interface = [[CocoaInterface alloc] init];
cout << "Calling CocoaInterface::ShowFileDownloadDialog." << endl;
[interface ShowFileDownloadDialog];
这会在尝试执行选择器时挂起——好像它永远无法真正找到主线程。 GDB 中的回溯显示我一直在等待信号量。
当我在 performSelectorOnMainThread 调用之前取消注释 NSRunAlertPanel 调用时,我得到一个对话框形状的白色块,但它没有完全绘制或处理任何消息,可能是因为它不在主 GUI 线程上。
似乎我没有合适的 GUI 线程,或者无法从我所在的位置访问它。我怀疑我在初始化中遗漏了一些东西。有什么建议吗?
【问题讨论】:
标签: multithreading cocoa user-interface macos objective-c++