从线程中的C函数更新UI [英] updating UI from a C function in a thread

查看:109
本文介绍了从线程中的C函数更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在iPhone应用程序中使用一个名为libmosquitto的库.

I am using a library called libmosquitto in an iPhone app.

该库是用C编写的. 它接收推送通知,因此在线程中运行.

The library is written in C. It receives push notifications and therefor runs in a thread.

我想获取接收到的数据,并将其显示在UITableView中,但是(我认为)我必须编写libmosquitto用作C函数而不是Objective C方法的回调,因此我无法在其中访问'self'要做的事情: [self performSelectorOnMainThread:@selector(hideActivityViewer)withObject:nil waitUntilDone:NO];

I want to take the data it receives, and display it in a UITableView, however ( I think) I have to write the callbacks which libmosquitto uses as C functions rather than Objective C methods, so I cannot access 'self' in order to do: [self performSelectorOnMainThread:@selector(hideActivityViewer) withObject:nil waitUntilDone:NO];

任何人都有这样的问题,还有其他方法可以更新用户界面吗?

Anyone have problems like this, is there another way I could update the UI?

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

From inside one of my Objective C methods I call this:

mosquitto_message_callback_set(mosq, my_message_callback); 

my_message_callback定义为:

And my_message_callback is defined as:

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);

}

谢谢

推荐答案

函数mosquitto_newvoid *指针作为第二个参数,然后它将传递给您拥有的任何回调.您可以使用它来传递self,因为应该作为void *obj到达回调的东西.然后,将其强制转换为正确的[pointer to]类类型是绝对安全的,因为C允许将任何指针类型都转换为void *(并返回)而没有任何副作用.

The function mosquitto_new takes a void * pointer as the second argument, which it will then pass to any callbacks that you have. You can use that to pass self as the thing that should arrive at your callback as void *obj. It's then explicitly safe to cast that to the correct [pointer to] class type since C allows any pointer type to be converted to void * (and back) without any side effects.

因此,您将执行以下操作:

So then you'd do something like:

void my_message_callback(void *obj, struct mosquitto_message *message)
{
    [(ClassType *)obj
        performSelectorOnMainThread:@selector(updateTable)
        withObject:nil
        waitUntilDone:NO];
}

这篇关于从线程中的C函数更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆