在NSOperationQueue中发布通知

时间:2015-07-05 13:15:19

标签: ios objective-c notifications nsnotificationcenter nsoperationqueue

我需要你帮助NSNotificationCenter。我有一个名为Sensor的班级和一个名为SensorManager的班级。我想从SensorSensorManager发送通知。在SensorManager中我写了这段代码:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveTestNotification:) name:@"TestNotification" object:nil];

显然,我有这个功能:

- (void) receiveTestNotification:(NSNotification *) notification
{                
    if ([[notification name] isEqualToString:@"TestNotification"])
        NSLog (@"Successfully received the test notification!");
}

在Sensor类中,我有一个启动传感器的功能:

-(void)workSensor{               
        self.motionManager.accelerometerUpdateInterval = 0.05;

        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        [self.motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *data, NSError *error) {                
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self];

            NSLog(@"Udapte iphone acc data!");
        }];
    }

}

不幸的是,SensorManager没有收到通知。奇怪的是(从我的角度来看)是如果我将通知代码移到NSOperationQueue块之外,一切都很好(参见下面的代码):

-(void)workSensor{    
            //now the notification is here. Outside the block.
            [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self];

            self.motionManager.accelerometerUpdateInterval = 0.05;

            NSOperationQueue *queue = [[NSOperationQueue alloc]init];
            [self.motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *data, NSError *error) {                


                NSLog(@"Udapte iphone acc data!");
            }];
        }

    }

如何将通知发件人放在NSOperationQueue块内?谢谢!

1 个答案:

答案 0 :(得分:0)

通知应该贴在主线程上,所以你应该这样:

[self performSelectorOnMainThread:@selector(sendNotification) withObject:nil waitUntilDone:YES];

将调用主线程上的函数。然后定义通知发送功能:

- (void)sendNotification {
  [[NSNotificationCenter defaultCenter] postNotificationName:@"myEventName" object:self]; 
}