我正在使用新的 CoreMotion 框架来监控一些硬件设备。这是执行此操作的典型代码:
-(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 框架让您使用块,因此不能保证它在主队列中(实际上不适用于我的应用程序)。像这样在主队列上运行标签的设置器是“错误的”吗?
-(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]];
}
它工作得很好,我真的看不出有什么理由会不赞成。对此有什么想法吗?