在辅助队列中执行UI更新 [英] Perfoming UI updates in secondary queue

查看:35
本文介绍了在辅助队列中执行UI更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的CoreMotion框架监视某些硬件设备.这是执行此操作的典型代码:

I am using the new CoreMotion framework to monitor some of the hardware devices. Here is the typical code to do that:

-(void)startAccelerometer{
self.motion.accelerometerUpdateInterval = 1/30.0f;
NSOperationQueue* accelerometerQueue = [[NSOperationQueue alloc] init];
CMAccelerometerHandler accelerometerHandler = ^(CMAccelerometerData *accelerometerData, NSError *error) {

    NSLog(@"Accelerometer realtime values");
    NSLog(@"x=%f", accelerometerData.acceleration.x);
    NSLog(@"y=%f", accelerometerData.acceleration.y);
    NSLog(@"z=%f", accelerometerData.acceleration.z);
    NSLog(@"  ");

};
[self.motion startAccelerometerUpdatesToQueue:accelerometerQueue withHandler:[[accelerometerHandler copy]autorelease]];

}

那很好.现在,我想在UILabel上打印值,但是由于CoreMotion框架让您使用了块,因此不能保证它位于主队列中(实际上不是针对我的应用程序).像这样在主队列上运行标签的setter是错误的"吗?

That works just fine. Now I want to print the values on a UILabel, but since the CoreMotion frameworks has you use blocks, this is not guaranteed to be in the main queue (and in fact isn't for my app). Is it is "wrong" to just run the label's setter on the main queue like this?

-(void)startAccelerometer{
self.motion.accelerometerUpdateInterval = 1/30.0f;
NSOperationQueue* accelerometerQueue = [[NSOperationQueue alloc] init];
CMAccelerometerHandler accelerometerHandler = ^(CMAccelerometerData *accelerometerData, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.lblAccelerometer.text = [NSString stringWithFormat:@"Accelerometer:\nx = %f\ny = %f\nz = %f",
                                      accelerometerData.acceleration.x,
                                      accelerometerData.acceleration.y,
                                      accelerometerData.acceleration.z];

    });

};
[self.motion startAccelerometerUpdatesToQueue:accelerometerQueue withHandler:[[accelerometerHandler copy]autorelease]];

}

它工作得很好,我真的看不出有什么理由会对此皱眉.有什么想法吗?

It works just fine and I don't really see any reason why this would be frowned upon. Any thoughts on that?

推荐答案

这是我在许多项目中使用的常用方法.UI更新必须在主线程上进行.

This is a common method that I use in many projects. UI updates must occur on the main thread.

//Dispatch on background thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    //background processing goes here

    //Dispatch on main thread
    dispatch_async(dispatch_get_main_queue(), ^{
            //update UI here
    });
});

在您的情况下,您的UI更新在主线程上进行.因此,我无需担心任何更改.

In your case, your UI updates are occurring on the main thread. So I wouldn't worry about changing anything.

这篇关于在辅助队列中执行UI更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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