NSNotification postNotification和addObserver

时间:2014-06-09 01:20:40

标签: ios nsnotification

我正在尝试从位置管理器对象到我的viewController进行通知。它不起作用 - addObserver方法中的选择器不会被调用。

位置管理器Object.m文件(带有标准调度一次和初始化方法的单例)

- (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");

}

1 个答案:

答案 0 :(得分:1)

你做的不正确。为什么要添加观察者然后立即将其删除。大多数情况下,我们会在viewWillAppearviewWillDisappearviewDidAppearviewDidDisappear中添加/删除观察者。

应该是这样的: -

-(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];
}