Send NSNotification from AppDelegate

2.4k views Asked by At

I want to send an NSNotification from this method (when the UIButton is clicked) in my AppDelegate.m:

- (void)alertView:(UIAlertView *)alertView 
        clickedButtonAtIndex:(NSInteger)buttonIndex{

if (buttonIndex == 0){
    //cancel clicked ...do your action
    // HERE
}
}

..and receive it in one of my UIViewControllers. How can I do that?

EDIT WITH MORE INFO: I am making an alarm app, and when the user presses the UIButton, I want to stop the alarm. I figured that NSNotifications is the only way to get information from my AppDelegate.m file to a ViewController.m file?

2

There are 2 answers

4
dpizzuto On BEST ANSWER

You should to register your receiver object to accept some messages sent from Notification Center.

Suppose you have Obj A which controls your alarm, and value "stopAlarm" is the message which can stop alarm. You should create an observer for a "stopAlarm" message.

You can do, with:

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

Now, you should create a method controller that manages this messages:

 - (void)controller:(NSNotification *) notification {

     if ([[notification name] isEqualToString:@"stopAlarm"]){

         //Perform stop alarm with A object
     }
  }

Finally, you can send the message "stopAlarm" when you want in the code with:

[[NSNotificationCenter defaultCenter]
     postNotificationName:@"stopAlarm"
     object:nil];

I Hope this may help.

EDIT:

When your UIViewController are unloaded or when app terminate, you should call:

    [[NSNotificationCenter defaultCenter] removeObserver:self];

for stop observing. That's all.

Thanks to Hot licks for correction.

0
Chris On

You may want to create a class–maybe even a singleton if there is only one alarm–that manages the timer. That way you can manage from any place in your application rather than in the view controller. Take a look at:

http://dadabeatnik.wordpress.com/2013/07/28/objective-c-singletons-an-alternative-pattern/

and:

https://developer.apple.com/library/mac/documentation/cocoa/conceptual/Notifications/Articles/NotificationCenters.html

As Hot Licks mentioned, you really do not want to jump into this without knowing what is going on. Hopefully these links will help get you going in the right direction.