EXC_BAD_INSTRUCTION :任务线程失败可可
我正在编写一个应用程序来打印从服务器收到的消息。我在不同的线程中分离监听函数:
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:]
时,应用程序崩溃,并且我收到标题中的错误。如果我评论所有这些调用,则应用程序可以正常工作,并且我可以在控制台中读取正确的消息。
有什么建议吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
辅助线程实际上不应该接触 GUI。您需要将信息传递回主线程上的对象并更新文本视图。
来自线程编程指南:
Secondary threads aren't really supposed to touch the GUI. You'll need to pass the information back to an object on the main thread and have that update the text view.
From the Threading Programming Guide:
我不确定这是否是您问题的确切原因,但肯定可能是:您从未初始化
read
,因此您会不可预测地覆盖程序内存中的某些字节。它应该是这样的:尽管正如 Josh Caswell 指出的那样,所有这些
insertText:
消息都应该类似于[messagesView PerformSelectorOnMainThread:@selector(insertText:) withObject:@"\nConnection returned by远程主机\n" afterDelay:0]
。I'm not sure if this is the precise cause of your problem, but it certainly could be: You never initialize
read
, so you're unpredictably overwriting some byte in your program's memory. It should be something like:Though as Josh Caswell points out, all those
insertText:
messages should be something like[messagesView performSelectorOnMainThread:@selector(insertText:) withObject:@"\nConnection closed by remote host\n" afterDelay:0]
.