10

I am trying to call a method within an uiview from AppDelegate using the NSNotificationCenter to no avail..

AppDelegate.m

    [[NSNotificationCenter defaultCenter] postNotificationName:@"ProcessDidComplete" object:items];

Then via MainStoryboard, the main view is loaded which controller class is MainViewController

in MainViewController.h viewDidLoad i have

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ProcessDidComplete:) name:@"ProcessDidComplete" object:nil];

and then the method

- (void) ProcessDidComplete:(NSNotification *)pNotification

but it never gets called.

Thanks for any help!

spacebiker
  • 3,777
  • 4
  • 30
  • 49

3 Answers3

17

just change a way..

First add observer

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ProcessDidComplete:) name:@"ProcessDidComplete" object:nil];

Then Post Notification

 [[NSNotificationCenter defaultCenter] postNotificationName:@"ProcessDidComplete" object:items];

Finally remove in viewWillDisappear

 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ProcessDidComplete" object:nil];
Rams
  • 1,721
  • 12
  • 22
  • 1
    Woah! that was fast. Thanks for your reply. You pointed me in the right direction. postNotificationName is being called before the observer is created, so now the question is.. taking into account i load the views using the storyboard, how could i make it to addObserver before posting the notificacion as the postNotificationName is called in AppDelegate's didFinishLaunchingWithOptions and the observer is added in the viewDidLoad from the MainView.. thanks in advance – spacebiker Mar 13 '12 at 11:02
  • I haven't implemented storyboard..Better you try addobserver in appdidfinishlaunching method. – Rams Mar 13 '12 at 11:16
5

Your code looks okay, which makes me wonder where in your app delegate you post the notification?

If you post the notification before you add the observer in the view controlller, then the notification will never be received. Can you not send the message to the main view controller directly, i.e., as a property, rather than using notifications?

Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152
  • hi mate, thanks for the reply. the notification is post in the didFinishLaunchingWithOptions and the observer is created in the MainView's viewDidLoad, because i am using story board, the MainView is loaded too late. Do you have any suggestion ? – spacebiker Mar 13 '12 at 11:07
0

Just wanted to note here that iOS notification names are case-sensitive:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handUpdate:) name:@"scheduleUpdated" object:nil];

will not respond to:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ScheduleUpdated" object:items];

(as I spent the last 20 minutes figuring out...)

adamup
  • 1,508
  • 19
  • 29