Notification mechanism simplified (swift)

The aim of this post is to explain and provide an example about notification mechanism simplified (,but not simplistic) in swift. The first thing that you need to be clear is when to use this mechanism and when delegate mechanism.

Both mechanism help to decouple view controllers. Notifications offer the advantage that multiple objects can observer one notifications.  In delegate mechanism the communication is direct (through a protocol method implementation) with the delegate class.

The example that I am going to present to shows the notification mechanism as a broadcast service. A timer periodically will launch a notification, on the other side there will be two classes (Alice and Bob) that will be intercepting the message.

As you can see in the code every 3 seconds is sent a notification that is intercepted by Alice and Bob class in the following way:

Is important to keep under control when to unsubscribe to the notification mechanism. In case of Alice is after receiving 3 messages and in case of Bob is when the class is removed from memory.

Once we run the project we should have to see the following in the log window:


You can find the sample project here.






Leave a Reply

Your email address will not be published.