首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSNotification postNotification和addObserver

NSNotification postNotification和addObserver
EN

Stack Overflow用户
提问于 2014-06-09 01:20:39
回答 1查看 317关注 0票数 1

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

LocationManagerObject.m文件(标准分派一次和init方法的单例)

代码语言:javascript
复制
- (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 (花园品种)

代码语言:javascript
复制
- (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");

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-09 01:29:41

你这样做是不对的。为什么要添加观察者,然后立即删除它。大多数情况下,我们在viewWillAppearviewWillDisappearviewDidAppearviewDidDisappear中添加/删除观察者。

应该是这样的:

代码语言:javascript
复制
-(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];
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24112544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档