618

I am attempting to send and receive messages through NSNotificationCenter in Objective-C. However, I haven't been able to find any examples on how to do this. How do you send and receive messages through NSNotificationCenter?

hichris123
  • 9,735
  • 15
  • 51
  • 66
  • Really very useful, thanks. One thing, the addObserver method shouldn't have the trailing semi colon after the specified selector (at least it caused an exception in my version of this). I tried editing the code above but the change was not accepted due to formatting issues in the original code. – Braunius Oct 05 '11 at 08:02
  • 3
    This was great: http://cocoawithlove.com/2008/06/five-approaches-to-listening-observing.html – Aram Kocharyan Feb 13 '12 at 05:35
  • 2
    this q is way too basic and broad, a little googleing would have beeen good – Daij-Djan Nov 14 '12 at 07:52
  • This is very similar to a related question here: http://stackoverflow.com/questions/7896646/how-to-pass-object-with-nsnotificationcenter – David Douglas Jun 21 '14 at 09:49
  • 56
    I find it absurd a question like this is closed an not constructive when the users of Stack Overflow have so clearly commented its usefulness – Chet Jul 31 '14 at 01:06
  • Instead of NSNotificationCenter, try ObserversCenter: https://github.com/yonglam/ObserversCenter – Andrew Mar 03 '15 at 05:55
  • If you are using `NSNotificationCenter` I recommend you usage of library https://github.com/AllinMobile/AIMObservers which helps to avoid common mistakes – Maciej Gad Dec 12 '15 at 18:29

6 Answers6

1032
@implementation TestClass

- (void) dealloc
{
    // If you don't remove yourself as an observer, the Notification Center
    // will continue to try and send notification objects to the deallocated
    // object.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (id) init
{
    self = [super init];
    if (!self) return nil;

    // Add this instance of TestClass as an observer of the TestNotification.
    // We tell the notification center to inform us of "TestNotification"
    // notifications using the receiveTestNotification: selector. By
    // specifying object:nil, we tell the notification center that we are not
    // interested in who posted the notification. If you provided an actual
    // object rather than nil, the notification center will only notify you
    // when the notification was posted by that particular object.

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

    return self;
}

- (void) receiveTestNotification:(NSNotification *) notification
{
    // [notification name] should always be @"TestNotification"
    // unless you use this method for observation of other notifications
    // as well.

    if ([[notification name] isEqualToString:@"TestNotification"])
        NSLog (@"Successfully received the test notification!");
}

@end

... somewhere else in another class ...

- (void) someMethod
{

    // All instances of TestClass will be notified
    [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"TestNotification" 
        object:self];

}
beggs
  • 4,158
  • 2
  • 27
  • 30
dreamlax
  • 89,489
  • 28
  • 156
  • 207
  • 2
    Just wondering where [NSNotificationCenter defaultCenter] is meant to placed. Is it best to place it in your AppDelegate? – fulvio Jan 12 '11 at 06:17
  • 15
    @Fulvio: It depends, if you are receiving or posting notifications that potentially affect all parts of your application, put it in your AppDelegate. If you are receiving/posting notifications that only affect a single class, put it in that class instead. – dreamlax Jan 12 '11 at 08:34
  • Also, note that "The method specified by notificationSelector must have one and only one argument (an instance of NSNotification)". I initially assumed that you could provide a selector without an argument and forgo the NSNotification. – Aram Kocharyan Feb 13 '12 at 06:35
  • 1
    @dreamlax Truth, however it's worth noticing because this question is mostly searched by new ios devs who keep the notification listener alive longer than they need. Now with arc you usually don't use dealloc and as a result some may think they don't have to release the listener. – Nat Nov 05 '13 at 07:45
  • dream, perhaps you should consider also adding the definitive example for a *distrubuted* notification. – Fattie Nov 27 '13 at 13:40
  • 7
    It might also be worth mentioning that the `[super dealloc]` call in the dealloc-method is not permitted under ARC; the rest is all good. – tommys Feb 19 '14 at 18:02
  • NB! if supposing multithread then placing removeObserver to dealloc is not so good idea. Here simple example to crash: http://lapcatsoftware.com/articles/nsnotificationcenter-is-threadsafe-not.html – Maxim Kholyavkin Oct 23 '14 at 10:39
  • It seems that all that observer idea doesn't cover all cases. this didn't work when the app. was closed and a notification form the notification centre got tapped. observer method doesn't get called. – hasan Jan 14 '15 at 12:27
  • 1
    What happen if the notification fires and there are no observers? Is notification lost? Or is it "saved" somewhere ready to be shipped to a new observer (created later)? – matteopuc Feb 27 '15 at 12:19
  • 1
    @superpuccio: If there are no observers, then nothing happens, the NSNotification is simply discarded. – dreamlax Feb 27 '15 at 13:56
  • @dreamlax: I am facing an issue with your code. In my simple app, there are two viewcontrollers. In the first VC, I have given a button, which when pressed, sends out the 'TestNotification' and performs a segue to the other VC, which is the Observer in my case. I have declared the observer as self in this and rest, as is your code.The problem is the method 'receiveTestNotification' doesn't gets called at all..! Not even once! It doesn't gets called anyway. And I have crossed checked with your code,so there is hardly any difference.So, would you mind helping me or guide appropriately. – Archit Kapoor Dec 31 '15 at 10:49
  • @ArchitKapoor: Check to make sure you are not posting the notification from a background thread. You can only update the user interface from the main thread. – dreamlax Dec 31 '15 at 10:54
  • @dreamlax: The notification is posted from the main thread; when the button is pressed an IBAction is called where in I post the notification and perform the segue thereafter in the same method. The code where I am posting the Notification is: [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:[[ObserverViewController alloc] init]]; – Archit Kapoor Dec 31 '15 at 11:03
  • @dreamlax: I also tried this: [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self]; But my efforts went in vain. – Archit Kapoor Dec 31 '15 at 11:08
  • To avoid the message "ARC forbids explicit message send of 'dealloc' " just remove the invocation to its super class`[super dealloc]`, like: ```-(void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; }``` also add the observer to the main queue to avoid more problems. – Pedro Trujillo Oct 24 '18 at 16:31
232

To expand upon dreamlax's example... If you want to send data along with the notification

In posting code:

NSDictionary *userInfo = 
[NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName: 
                       @"TestNotification" object:nil userInfo:userInfo];

In observing code:

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

    NSDictionary *userInfo = notification.userInfo;
    MyObject *myObject = [userInfo objectForKey:@"someKey"];
}
Community
  • 1
  • 1
Michael Peterson
  • 9,046
  • 3
  • 51
  • 48
  • TestNotification must be NSString type. Is it an instance variable NSNotification? – RomanHouse May 02 '12 at 18:50
  • 1
    Can I access observer `self` in receiveTestNotification method ? – why Feb 26 '13 at 09:08
  • why - Yes. receiveTestNotification is an instance method, and you have access to the instance itself via self within it. – Michael Peterson Aug 01 '14 at 22:01
  • That's it. I was looking for a way to get the UserInfo from the receiver method. – hasan Jan 14 '15 at 11:58
  • It seems that all that observer idea doesn't cover all cases. this didn't work when the app. was closed and a notification form the notification centre got tapped. observer method doesn't get called. – hasan Jan 14 '15 at 12:26
  • I already do all that. I want to know the best way to open the view controller. I am enhancing code now. I may get back to here with a question when I finish. – hasan Jan 15 '15 at 08:15
  • @P1X3L5 Hey dude can you tell me what is the use of argument in adding a observer or posting a notification, since one can pass the date in **userinfo** – zeal May 22 '15 at 19:15
  • @zeal I've never used the argument. From the documentation it is described as "The object posting the notification." That may be useful if multiple objects were posting the same notification and you needed to take different action based on where it originated from. https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class – Michael Peterson May 25 '16 at 17:03
  • @YumYumYum could you post a little more of the code you're having a problem with and detail about the error you get? – Michael Peterson Feb 18 '17 at 17:11
52

This one helped me:

// Add an observer that will respond to loginComplete
[[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(showMainMenu:) 
                                                 name:@"loginComplete" object:nil];


// Post a notification to loginComplete
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginComplete" object:nil];


// the function specified in the same class where we defined the addObserver
- (void)showMainMenu:(NSNotification *)note {
    NSLog(@"Received Notification - Someone seems to have logged in"); 
}

Source: http://www.smipple.net/snippet/Sounden/Simple%20NSNotificationCenter%20example

j7nn7k
  • 15,623
  • 18
  • 73
  • 86
50

There is also the possibility of using blocks:

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] 
     addObserverForName:@"notificationName" 
     object:nil
     queue:mainQueue
     usingBlock:^(NSNotification *notification)
     {
          NSLog(@"Notification received!");
          NSDictionary *userInfo = notification.userInfo;

          // ...
     }];

Apple's documentation

Xavi Gil
  • 10,764
  • 3
  • 51
  • 67
  • 1
    This is a good update to my answer which is fairly outdated now. With the introduction or ARC and blocks, notification centres are much easier to deal with. – dreamlax Apr 24 '13 at 17:14
  • 5
    I thought so too, but it turns out that it's too good to be true. In this case you have to retain the observer that addObserver returns and later on remove that, which makes it as complicated as creating a new method, if not more so. More info: http://toastmo.com/blog/2012/12/04/be-careful-using-nsnotificationcenter/ – Andrew Aug 27 '13 at 12:34
43

if you're using NSNotificationCenter for updating your view, don't forget to send it from the main thread by calling dispatch_async:

dispatch_async(dispatch_get_main_queue(),^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"my_notification" object:nil];
});
chug2k
  • 4,371
  • 2
  • 22
  • 30
eiran
  • 1,360
  • 15
  • 16
  • 1
    is it the notification post that needs to occur from the main thread, or just when you actually update the view, i.e., inside the method receiving the notification you dispatch to the main thread? – Crashalot Apr 19 '16 at 04:46
  • 1
    the thread you send the notification from is the thread running the functions, and thus trying to change the UI. you can also use the dispatch to the main thread inside the functions, just like you said:D. should have the same result, perheps it's even better:D – eiran Apr 19 '16 at 09:29
  • 1
    @eiran, thank you so much bro, it worked only after i wrote inside dispatch_async – Arshad Shaik Aug 06 '19 at 06:49
8

SWIFT 5.1 of selected answer for newbies

class TestClass {
    deinit {
        // If you don't remove yourself as an observer, the Notification Center
        // will continue to try and send notification objects to the deallocated
        // object.
        NotificationCenter.default.removeObserver(self)
    }

    init() {
        super.init()

        // Add this instance of TestClass as an observer of the TestNotification.
        // We tell the notification center to inform us of "TestNotification"
        // notifications using the receiveTestNotification: selector. By
        // specifying object:nil, we tell the notification center that we are not
        // interested in who posted the notification. If you provided an actual
        // object rather than nil, the notification center will only notify you
        // when the notification was posted by that particular object.

        NotificationCenter.default.addObserver(self, selector: #selector(receiveTest(_:)), name: NSNotification.Name("TestNotification"), object: nil)
    }

    @objc func receiveTest(_ notification: Notification?) {
        // [notification name] should always be @"TestNotification"
        // unless you use this method for observation of other notifications
        // as well.

        if notification?.name.isEqual(toString: "TestNotification") != nil {
            print("Successfully received the test notification!")
        }
    }
}

... somewhere else in another class ...

 func someMethod(){
        // All instances of TestClass will be notified
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "TestNotification"), object: self)
 }
Maneesh M
  • 143
  • 1
  • 9