Duck
Duck

Reputation: 36003

iPhone - delegate or notification?

You have a class that has to send a message to its parent. This class is not used by any other member of your application. You send the message as a NSNotification or you create a delegate protocol on that class and implement the delegate method in the parent, so you can send the message?

What is the best approach and why? There's any advantage of one method over the other?

Thanks

Upvotes: 3

Views: 513

Answers (2)

isaac
isaac

Reputation: 4897

While both approaches could be used to satisfy the described messaging requirement, a delegate protocol is the better suited choice in this case.

The benefit of notification as pattern is that many objects may respond to a notification which has been posted. An object wishing to observe notifications need only register to receive them. An advantage to this is that your code is very loosely coupled (generally a desirable value in oop). The drawback to the loose coupling in this case is the fact that you have potentially related behavior occurring across different classes and essentially all over your code base.

A delegation pattern is more tightly coupled, and your delegate object must conform to the protocol of the object it will receive messages from. Because of this, it is relatively easy to observe the nature of the interaction (or intended interaction) between the notifying object and the notified object - it's easier to grasp, simply by looking at the code, object messaging between two "related" objects. In a case where you have a child essentially announcing some behavior (which is directly related to the behavior of the parent, presumably), I think delegation is a superior approach.

Upvotes: 4

Michael Dautermann
Michael Dautermann

Reputation: 89519

Notifications is useful for when you have multiple observers or objects that are interested in the notification. They're also useful for Key Value Observing.

Delegates are very useful for sending a message (which conforms to the protocol that you declare) from one object to another object designated as the delegate target.

Upvotes: 5

Related Questions