cocoa - EXC_BAD_指令: task_thread failed cocoa

标签 cocoa macos sockets

我正在编写一个应用程序来打印从服务器收到的消息。我在不同的线程中分离监听函数:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
char *read;

do {
    chk = (int) recv(connfd, read, 1, 0);

    if(chk==-1) {
        printf("Error in recv(): connfd = %d\n",connfd );
        perror(err);
    }
    else if (chk ==0) {
        [messagesView insertText:@"\nConnection closed by remote host\n"];
        printf("Connection closed by remote host\n");
    }
    else {
        if( *read == '\n') {
            [messagesView insertText:@"\\n\n"];
            printf("\\n");
        }
        else if (*read == '\r') {
            [messagesView insertText:@"\\r\r"];
            printf("\\r");
        }
        else {
            [messagesView insertText:[NSString stringWithFormat:@"%c",*read]];
            printf("%c", *read);
        }
        printf(" -- %d\n",*read);
    }
}   while (chk>0);

[pool drain];

chk 和 connfd 是 int,messagesView 是 NSTextView*。 当我调用 [messagesView insertText:] 时,应用程序崩溃,并且在标题中收到错误。如果我评论所有这些调用,则应用程序可以正常工作,并且我可以在控制台中读取正确的消息。 有什么建议吗?

最佳答案

辅助线程实际上不应该接触 GUI。您需要将信息传递回主线程上的对象并更新 TextView 。

来自Threading Programming Guide :

Threads and Your User Interface
If your application has a graphical user interface, it is recommended that you receive user-related events and initiate interface updates from your application’s main thread. This approach helps avoid synchronization issues associated with handling user events and drawing window content. Some frameworks, such as Cocoa, generally require this behavior, but even for those that do not, keeping this behavior on the main thread has the advantage of simplifying the logic for managing your user interface.

关于cocoa - EXC_BAD_指令: task_thread failed cocoa,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5704711/

相关文章:

java - Spring log4j 无法在 osx 上保存日志文件

java - Java for OS X 2013-004 如何影响(破坏)Swing 应用程序?

python - C 和 Python 之间的 Unix 套接字

C/Linux TCP 套接字服务器

cocoa - 为什么在 Mac 上, NSReadPixel() 会导致 "_NSReadPixel",从 : _main in cctJJibI. o ld : symbol(s) not found? 引用

objective-c - 阅读码头信息 OSX?

objective-c - 澄清 Cocoa 语法中的星号和下划线

objective-c - 类转储 z 生成空 header

c++ - QDesktopServices::openUrl() 无法在 MAC Finder 中打开目录

java - read() 和 readObject() 的问题