我需要你帮助NSNotificationCenter
。我有一个名为Sensor
的班级和一个名为SensorManager
的班级。我想从Sensor
向SensorManager
发送通知。在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
块内?谢谢!
答案 0 :(得分:0)
通知应该贴在主线程上,所以你应该这样:
[self performSelectorOnMainThread:@selector(sendNotification) withObject:nil waitUntilDone:YES];
将调用主线程上的函数。然后定义通知发送功能:
- (void)sendNotification {
[[NSNotificationCenter defaultCenter] postNotificationName:@"myEventName" object:self];
}