Search code examples
iosobjective-cnsnotificationcenter

NSNotificationCenter doesn't work in popup view(ios objC)


I'm working on a iPad project(xcode 7.21+iOS9) and NSNotificationCenter doesn't work.

When user open my app, the tab bar controller will appear.

- (void)viewWillAppear:(BOOL)animated {
    if (false == [[MyClass sharedData] getLoginStatus])
    {
        LoginViewController *loginViewController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"myCustomPopoverLoginVC"];
            loginViewController.modalPresentationStyle = UIModalPresentationFormSheet;
            [self presentViewController:loginViewController animated:YES completion:^{

        }];
...
    }
}

- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationLogin:) name:@"afterLogin" object:nil];
    [super viewDidLoad];
...
}

-(void)notificationLogin:(NSNotification *)notification{
    NSLog(@"OhOhOh");
}

In my loginView,

-(IBAction)login:(id)sender{
    ...
    [[NSNotificationCenter defaultCenter] postNotificationName:@"afterLogin" object:nil];
    ...
}

Solution

  • First of all:

    - (void)viewWillAppear:(BOOL)animated {
        if (false == [[MyClass sharedData] getLoginStatus])
        {
            LoginViewController *loginViewController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"myCustomPopoverLoginVC"];
                loginViewController.modalPresentationStyle = UIModalPresentationFormSheet;
                [self presentViewController:loginViewController animated:YES completion:^{
    
            }];
    ...
        }
    }
    
    - (void)viewDidLoad
    {
        // Add log here to check when its called
        -------> NSLog("Add Observer");
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationLogin:) name:@"afterLogin" object:nil];
        [super viewDidLoad];
    ...
    }
    
    -(void)notificationLogin:(NSNotification *)notification{
        NSLog(@"OhOhOh");
    }
    

    then add another log here :

    -(IBAction)login:(id)sender{
        ...
        -------> NSLog("Post notification");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"afterLogin" object:nil];
        ...
    }
    

    So you can check what called first. Then refer @Sandeep Kumar comment :)) NSNotificationCenter doesn't work in popup view(ios objC)