Discuss the role of 'NotificationCenter' in iOS and how it differs from delegation.

Instruction: Explain how 'NotificationCenter' is used for communication in iOS apps and compare it with the delegate pattern.

Context: This question tests the candidate's understanding of different communication patterns in iOS, specifically 'NotificationCenter' and delegation, highlighting their use cases and differences.

Updated

Official answer

NotificationCenter distributes in-process events to interested observers. The sender need not know each observer, which suits a shared preference or application-state change. It is not APNs, a persistent message queue or a guarantee that an observer was present when an event occurred.

The familiar block observer API takes a notification name, optional sender, queue and closure, and returns an observer token. Keep that token and remove the registration when its owner no longer needs updates. The center retains the block; a block that strongly captures an owner which retains the token can create a cycle. Weak capture and explicit removal serve different purposes: one controls ownership, the other stops observation.

With queue:nil, this block API runs synchronously on the posting thread, so posting can execute observer work and reenter application code. Do not assume UI-thread delivery or universal observer ordering. Use an appropriate queue/isolation strategy and validate payload types. Newer typed notification-message APIs offer stronger contracts on supported OS versions; check availability instead of mixing them into an older deployment target without a fallback.

Delegation usually appoints one collaborator through a protocol and can request a direct decision. It exposes the expected relationship more explicitly. For UITableView, the data source provides rows/cells, while the delegate handles interactions and presentation choices; those are distinct protocols even when one controller implements both.

Choose notification broadcasting for genuine multiple-observer events and a delegate or callback for a specific owner's response. Keep authoritative state elsewhere so a late subscriber can obtain the current value, and test duplicate registrations, removal, reentrancy and sender filtering.

NotificationCenter, Block observer lifetime and queue, UITableView data source

Related Questions