NSNotification Center仅在第二次工作? TabbarController到NavigationController

时间:2016-08-18 09:29:02

标签: ios objective-c nsnotificationcenter nsnotifications

场景我有两个视图控制器:Tabcontroller和Viewcontroller。在第一个我定义我的帖子通知,在第二个我添加了一个观察者与接收方法。

在我的tabcontroller(发件人)上:

-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{

[[NSNotificationCenter defaultCenter] postNotificationName:@"RestartBtn" object:self userInfo:@{@"isHidden": @"YES"}];

}

在viewcontoller(接收方)上:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"HallOfFameView");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"RestartBtn" object:nil];

}
-(void)receiveNotification:(NSNotification*)notification {

    NSLog(@"%@",[notification name]);
    _restartbutton.hidden=YES;
    NSLog(@"%@",notification.userInfo[@"isHidden"]);
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self name:@"RestartBtn" object:nil];
    }

当我点击我的tabbaritem时,它将推送一个视图控制器,它将打印“HallOfFameView”,我相信这将注册观察者,但不是第一次只在第二次执行接收通知方法。例如,当我单击tabbar项目(“Home”)时,它将执行接收通知方法。

为什么不第一次工作?以及为什么它已经从我希望工作的viewcontroller退出(这是我添加观察者的地方)。

2 个答案:

答案 0 :(得分:2)

  1. 你是对的。视图控制器正在注册通知,但它不会收到通知。在视图控制器出现并注册之前,标签栏控制器已经触发了通知。

  2. 标签栏控制器正在为每个被选中的标签发布该通知。因此,当您点击另一个标签栏项目时,通知会被发布,现在视图控制器 已存在并接收它。

  3. 看起来你要做的就是将标签栏控制器中的信息传递给视图控制器。可能有更好的方法来做到这一点。

    如果您正在使用故事板,则标签栏控制器将使用segue移动到视图控制器场景。您可以在标签栏控制器上查看覆盖此方法:- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender,这将使您有机会在“目标视图控制器”上设置属性。

答案 1 :(得分:0)

在viewWillAppear方法中添加观察者编码,并在viewWillAppear中删除观察者

- (void)viewWillAppear:(BOOL)animated
{
   [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RestartBtn" object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"RestartBtn" object:nil];
}