NSOperationQueue并将委托发送给主线程

时间:2012-02-16 16:23:52

标签: iphone objective-c ios

嗨,我有我的班级传感器,我有gps,陀螺仪,加速度计,我想从nsoperationqueue代表发送数据:

@protocol SensorsDelegate <NSObject>
@optional
- (void)motionManagerDidAccelerateData:(CMAccelerometerData *)accelerometerData;
@end


- (void)startAccelerometr
{
    if (motionManager.accelerometerAvailable) {

        self.motionManager.accelerometerUpdateInterval = 1.0/10.0;
        [self.motionManager startAccelerometerUpdatesToQueue:self.operationQueue 
          withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
            if (error) {
                [motionManager stopAccelerometerUpdates];
            }
            else {
                [self.delegate motionManagerDidAccelerateData:accelerometerData];
            }
        }];
    }
}

如何将数据发送到主线程中的委托?或发送acceleremoter数据?

4 个答案:

答案 0 :(得分:2)

onMainThread:方法放在同一个类中并像这样更改代码

- (void)startAccelerometr
{
        if (motionManager.accelerometerAvailable) {

        self.motionManager.accelerometerUpdateInterval = 1.0/10.0;
        [self.motionManager startAccelerometerUpdatesToQueue:self.operationQueue 
          withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
            if (error) {
                [motionManager stopAccelerometerUpdates];
            }
            else {
                [self performSelectorOnMainThread:@selector(onMainThread:)
                  withObject:accelerometerData waitUntilDone:NO];
            }
        }];
    }
}

- (void)onMainThread:(id)accelerometerData{
    [self.delegate motionManagerDidAccelerateData:accelerometerData];
}

答案 1 :(得分:2)

您是否尝试过使用

[self.delegate performSelectorOnMainThread:@selector(motionManagerDidAccelerateData:) withObject:accelerometerData waitUntilDone:NO];

答案 2 :(得分:2)

您可以尝试:

假设委托是在Sensor init方法分配的NSObject<SensorDelegate>*类型的属性:

[self.delegate performSelectorOnMainThread:@selector(motionManagerDidAccelerateData:) withObject:accelerometerData waitUntilDone:NO];

希望它有所帮助。

答案 3 :(得分:1)

将正在发送加速度计更新的队列更改为主队列。

    [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {