swiftclosuresnsnotificationcenter

NotificationCenter or Closure?


For the supervisors: I have searched a lot before I decided to ask this question but I didn't find exactly what I want.

My question is: Which is better between using NotificationCenter and using Closures to communicate between two instances? If they are similar, what should I use?

Hopefully, this example helps you to understand better:-

If we take URLSession class as an example. Why do most of its methods have a closure? Why do not they send a notification with Data, Response, and Error inside it?

I know the difference between them, I just don't know in what situations should I use each one.


Solution

  • In some cases the patterns are interchangeable, however:

    1. Using a closure is the simplest solution for simple cases
    2. Using a delegate is common when there is complex communication between two objects. One delegate can be better than many closures.
    3. You have to use notifications when you have multiple observers or when you are not sure what objects will be observing.

    You might be asking yourself why we are using closures for simple cases and not delegates or notifications. The answer is that closures are the most lightweight. They are easy to create and they positively affect your code quality.

    Let's consider a completion callback. If you decide to use a notification, you need another method that will handle that notification. The same is valid for delegates. If you need some context (e.g. the parameters that triggered the actions), you will need to save it into a property.

    On the other hand, a closure can be created inline. That means that the code that triggers the action and handles its result is at one place. This really simplifies the structure of your code. Also note that if the closure needs some context, it can capture it, without the need to create an additional property.