skip to Main Content

I have two classes. A and B for example.

I have created an observer in A like this

- (void)viewDidLoad
      [[NSNotificationCenter defaultCenter] addObserver:self    selector:@selector(somethingHappens:) name:@"notificationName" object:nil];
}
    
-(void)somethingHappens:(NSNotification*)notification
 {
    NavigationController *navigationController = [self.storyboard instantiateViewControllerWithIdentifier:@"contentViewController"];
        
    UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"loyaltyVC"];
        navigationController.viewControllers = @[vc];

 }

I want to call this observe from page B. I’m using like this

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:self];

Do you have any suggestion how we can do this ?

2

Answers


    1. Have you tried to print a log in method somethingHappens:?
    2. Is your method -(void)didLoad ever been called?
    Login or Signup to reply.
  1. To be precise this are not push notifications. The following are just normal in-app-notifications.

    Your -(void)viewDidLoad should contain a call to its super method at some point.

    //in A
    @implementation AThingy {
        id<NSObject> observeKeeper;
    }
    - (void)viewDidLoad {
        [super viewDidLoad];
        observeKeeper = [[NSNotificationCenter defaultCenter] addObserverForName:@"notificationName" object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification * _Nonnull note) {
            UINavigationController *nav = [self.storyboard instantiateViewControllerWithIdentifier:@"contentViewController"];
            UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"loyaltyVC"];
            nav.viewControllers = @[vc];
        }];
    }
    // not mandatory but to explain it complete
    -(void)dealloc {
        // could be placed in some other method also.. like -viewDidDisappear:
        [[NSNotificationCenter defaultCenter] removeObserver:observeKeeper];
    }
    @end
    
    //in B
    @implementation BThingy
    -(void)postNotify {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:nil];
    }
    @end
    

    But keep in mind that NotificationCenter is working relative to its observing Objects and so it matters if you watch and post in general on (nil) or on some specific object. Why is that? Because you could decide to instantiate two objects from the same class that observe notifications and still specifically observe each notification meant for them or both.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search