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.
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:
import Cocoa class Consumer:NSObject { let nc = NSNotificationCenter.defaultCenter() override init() { super.init() nc.addObserver(self, selector: "printValue:", name: "printValue", object: nil) } func printValue(notification:NSNotification) { let userInfo:Dictionary= notification.userInfo as! Dictionary let item = userInfo["value"]! as String print(item,self) } } }
as you can see from the above code, the Consumer class shall:
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
class Producer { let nc = NSNotificationCenter.defaultCenter() init () { } func produce() { print("qui") nc.postNotificationName("printValue", object: nil, userInfo: ["value" : "9"]) } }
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.
var prod = Producer() var cons = Consumer() prod.produce()
the result will be the following.
9 <__lldb_expr_382.Consumer: 0x7ff929454e10>
If you’ll instantiate a second producer
var prod = Producer() var cons1 = Consumer() var cons2 = Consumer() prod.produce()
the result will be something like the following:
9 <__lldb_expr_375.Consumer: 0x7fb4f35543a0>
9 <__lldb_expr_375.Consumer: 0x7fb4f343f7b0>
Gg1