Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotificationCenter vs delegation( using protocols )?

What are the pros and cons of each of them?
Where should I use them specifically?

like image 396
EEE Avatar asked Dec 18 '09 12:12

EEE


People also ask

What is difference between protocol and delegate?

Protocol is a set of methods (either optional or required) that would be implemented by the class which conforms to that protocol. While, delegate is the reference to that class which conforms to that protocol and will adhere to implement methods defined in protocol. Have a look at this Apple doc for more detail.

What is the difference between a delegate and an Nsnotification?

Delegates, in much the same way, create a link between two objects, and you don't need to know what type the delegate will be, it simply has to implement the protocol. On the other hand, NSNotifications are like a radio station. They broadcast their message to whoever is willing to listen.

What is a delegation protocol?

Delegation works hand in hand with protocols because it allows a class to specify a delegate property which conforms to some protocol. Then a second class which actually conforms to that protocol can be assigned to that property.

What is delegate and notification in Swift?

use delegates when you want the receiving object to influence an action that will happen to the sending object. use notifications when you need to inform multiple objects of an event.


2 Answers

The rule of thumb here is how many clients would like to be notified of an event. If it's mainly one object (e.g. to dismiss a view or to act upon a button clicked, or to react to a failed download) then you should use the delegate model.

If the event you emit may be of an interest to many objects at once (e.g. screen rotated, memory usage, user login/logout), then you should use the NSNotificationCenter.

like image 88
notnoop Avatar answered Sep 22 '22 11:09

notnoop


Their purposes are different:

  • Notification is used to broadcast messages to possibly several recipients unknown from the sender.

  • Delegation is used to send messages to a single known recipient acting on behalf of the sender.

like image 28
mouviciel Avatar answered Sep 21 '22 11:09

mouviciel