【问题标题】:NSNotification postNotification and addObserverNSNotification postNotification 和 addObserver
【发布时间】:2014-06-09 01:20:39
【问题描述】:

我正在尝试从位置管理器对象向我的 viewController 发出通知。它不起作用 - addObserver 方法中的选择器没有被调用。

Location Manager 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");

}

【问题讨论】:

    标签: ios nsnotification


    【解决方案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];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多