objective-c - 从线程中的 C 函数更新 UI

标签 objective-c ios mqtt

我在 iPhone 应用程序中使用名为 libmosquitto 的库。

该库是用 C 语言编写的。 它接收推送通知并因此在线程中运行。

我想获取它接收到的数据,并将其显示在 UITableView 中,但是(我认为)我必须编写 libmosquitto 用作 C 函数而不是 Objective C 方法的回调,所以我无法访问“self”命令执行以下操作: [self PerformSelectorOnMainThread:@selector(hideActivityViewer) withObject:nil waitUntilDone:NO];

有人遇到这样的问题,还有其他方法可以更新 UI 吗?

在我的 Objective C 方法之一中,我称之为:

mosquitto_message_callback_set(mosq, my_message_callback); 

my_message_callback 定义为:

void my_message_callback(void *obj, struct mosquitto_message *message)
{
NSLog(@"Do this thing:");
if(message->payloadlen){
    const char *payload = (const char *)message->payload;
    [array addObject:[NSString stringWithUTF8String: payload]];
    //[self performSelectorOnMainThread:@selector(updateTable) withObject:nil waitUntilDone:NO];        

    //printf("%s %s\n", message->topic, message->payload);
}else{
    //printf("%s (null)\n", message->topic);
}
//fflush(stdout);

}

谢谢

最佳答案

查看 Grand Central Dispatch(GCD,又名 libdispatch)。它是一个 C 库,因此应该能够毫无问题地从您的 C 代码中调用。你想做类似的事情:

dispatch_async(dispatch_get_main_queue(), ^{
    //code you want on the main thread.
});

关于objective-c - 从线程中的 C 函数更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8010382/

相关文章:

iphone - Objective-C 检查下载文件的大小

ios - 解析 : Cannot sign up a user created automatically

ios - filterContentForSearchText :scope: method come from? 在哪里

objective-c - 有弹性的 UIBezierPath 线?

mqtt - 未知的配置变量 "protocol"错误 mosquitto

ios - Objective-C - 如何进行异常捕获并避免应用程序崩溃?

ios - 如何将 UIScrollview 的垂直滚动条更改为左侧站点?

java - 如何使用 Eclipse Paho 使用 Java MQTT 客户端仅发布一条消息

sockets - 使用 MQTT 而不是 RAW TCP/IP 套接字?

iphone - Objective-C 的 JSON 解析器比较(JSON 框架、YAJL、TouchJSON 等)