我正在尝试从位置管理器对象向我的viewController发出通知。它不起作用-- addObserver方法中的选择器没有被调用。
LocationManagerObject.m文件(标准分派一次和init方法的单例)
- (void)setCurrentLocation:(CLLocation *)currentLocation
{
if (!_location) {
_location = [[CLLocation alloc] init];
}
_location = currentLocation;
NSNumber *latitude = [NSNumber numberWithDouble:self.location.coordinate.latitude];
NSNumber *longitude = [NSNumber numberWithDouble:self.location.coordinate.longitude];
NSLog(@"lat %@ & long %@ in notification section", latitude, longitude);
NSNotification *notification = [NSNotification notificationWithName:@"myNotification" object:self userInfo: @{kSetLat: latitude,
kSetLong: longitude}];
[[NSNotificationCenter defaultCenter] postNotification:notification];
}ViewController.m (花园品种)
- (IBAction)welcomeNotification:(UIButton *)sender {
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(sendGetRequest:) name:@"myNotification" object:[LPLocationManager sharedManager]];
[center removeObserver:self];
NSLog(@"welcomeNotication triggered");
}发布于 2014-06-09 01:29:41
你这样做是不对的。为什么要添加观察者,然后立即删除它。大多数情况下,我们在viewWillAppear和viewWillDisappear或viewDidAppear和viewDidDisappear中添加/删除观察者。
应该是这样的:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendGetRequest:) name:@"myNotification" object:nil];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"myNotification" object:nil];
}https://stackoverflow.com/questions/24112544
复制相似问题