Swift NSNotificationCenter with userInfo (Producer/Consumer)

The Notification Center (NSNotificationCenter) provides a mechanism for broadcasting information within a program, it is a communication tool internal to your program.

Using the notification you can send messages (notification and data) from a class to another.

To receive a message, a class shall inherit from an NSObject and shall register with the Notification Center.
To send a message a class shall post the message to send to the Notification Center.

In the following few lines of code we are going to implement a Producer/Consumer program using the Notification Center, the code can be run inside a playground, so you don’t need to build a complete project.
broadcast
In our example the producer will post data to the Notification Center and any consumer registered to the NC will print out the data received from the producer.

Let’s start with the consumer:

as you can see from the above code, the Consumer class shall:

  • inherit from NSObject
  • instantiate the Notification Center
  • register to the Notification Center for the data it want to receive
  • create a selector to call each time a new message will arrive

    The producer is simpler, it shall instantiate the Notification Center then it shall post the message to the Notification Center

    To run the example you have to instantiate a producer and at least one consumer and then you have to call the produce method of the producer.

    the result will be the following.
    9 <__lldb_expr_382.Consumer: 0x7ff929454e10>

    If you’ll instantiate a second producer

    the result will be something like the following:
    9 <__lldb_expr_375.Consumer: 0x7fb4f35543a0>
    9 <__lldb_expr_375.Consumer: 0x7fb4f343f7b0>

    Gg1

    Related Posts

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.