Reputation: 618
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.
Upvotes: 4
Views: 1473
Reputation: 30746
I would say:
self
, e.g. when something is used in multiple closures being declared inline the closures will retain the thing as long as needed, saving you from needing to use deinit
.UIViewControllerShowDetailTargetDidChangeNotification
you can just listen within your child view controller which saves the parent from needing to manage a list of children to notify, which is tricky if the children are changing.UIApplicationDelegate
has less risk of messing up UIApplication
's standard behaviour like a subclass would (e.g. you forgot to call super or accidentally overrode a method with same name). It's best to have one delegate instance per target instance, e.g. don't make one instance be the delegate of multiple table views.Upvotes: 0
Reputation: 130152
In some cases the patterns are interchangeable, however:
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.
Upvotes: 9