Delegate or notification — when to choose which?
The point
These are three different ways to say "something happened", and the choice depends on the number of receivers and the strength of coupling:
- Delegate — one receiver, an explicit protocol contract, a
weakreference (AnyObjectprotocol); the sender knows a receiver exists and can get an answer back (shouldSelectRowreturns aBool). Examples:UITableViewDelegate,URLSessionDelegate. - Closure / callback — one receiver, a one-off or simple event (
onConfirm, a completion). Shorter than a delegate, but[weak self]is needed when stored. - NotificationCenter — many receivers, the sender knows none of them, loose coupling, no answer back. Examples:
keyboardWillShow, theme change, logout, system notifications.
On "synchronicity": a delegate and a closure are called directly, and notifications sent with post are also delivered synchronously on the sender's thread — this is not a selection criterion. The criterion is coupling and the number of subscribers.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep