gpt4 book ai didi

ios - NSNotification postNotification 和 addObserver

转载 作者:行者123 更新时间:2023-11-29 12:43:59 26 4
gpt4 key购买 nike

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

位置管理器 Object.m 文件(具有标准分派(dispatch)一次和初始化方法的单例)

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

}

最佳答案

你的做法不对。为什么添加观察者然后立即将其删除。大多数时候,我们在 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];
}

关于ios - NSNotification postNotification 和 addObserver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24112544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com