iPhone - delegate or notification? - iphone

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

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.

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.

Related

NotificationCenter or Closure?

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.
In some cases the patterns are interchangeable, however:
Using a closure is the simplest solution for simple cases
Using a delegate is common when there is complex communication between two objects. One delegate can be better than many closures.
You have to use notifications when you have multiple observers or when you are not sure what objects will be observing.
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.

Post single notification with varying object types

I have a class that acts as a wrapper around AVPlayer, and one of the functions it serves is to post notifications every 1 and 10 seconds during playback (ie make addPeriodicTimeObserverForInterval: more convenient in the general case).
Previously, the object I was sending with this notification was the player wrapper itself (ie ABPlayer.sharedPlayer). Today I had the need to allow for some objects to only receive notifications about a specific media item's playback. This can be accomplished by sending [[someAVURLAsset URL] absoluteString] as the notification object (when the asset in the AVPlayer is an AVURLAsset, of course).
The prompted the question: is it appropriate for a single notification to, in different situations, post with different types of objects? I understand the value in sending specific objects or sending nil (catch-all), but I don't recall seeing a situation where an alternative type of object could be sent. In my case, though, it seems to make sense.
I could simply send two distinct notifications, but since these are always only ever being sent to notify observers of a single event, and they are always being sent from the same place in code, they simply feel like a single notification.
I realize what I have is possible and working, but I'm curious if there's a compelling reason to avoid this pattern.
As long as the scenarios in which the different object types will be sent to the observers are well understood and documented, there's no technical reason why you can't do it. It may make more contextual sense to post a different notification for each object type. It would certainly help any developers who may end up maintaining your code.

Pros and Cons of Listener/Observer approaches to notify Model changes

In any typical iPhone application, there will be model classes that are responsible for data loading/parsing. Upon completion of the data loading/parsing tasks, the affected controllers needed to be notified of the change in the model and update the view accordingly.
There are several listener/observer approaches for this in iPhone application development. What are the pros/cons and reasons for using each of the following approaches?
KVO
NSNotification
Delegate
Any other known approach
In my own experience:
Delegation:
PRO: use only when you have a single object to notify;
PRO: using an explicit protocol you can document clearly your intentions;
CON: can be the source of crashes and memory leaks if wrongly used (tip: don't retain delegates, assign them, and remember to deassign delegates when / if they are released!)
I wrote about memory management problems generated by delegation in this article on my blog:
http://akosma.com/2009/01/28/10-iphone-memory-management-tips/
NSNotification:
PRO: better when you have several objects to notify;
PRO: very flexible, leads to loosely-coupled classes;
CON: notifications are sent synchronously (so make sure your individual notification handlers only do very little)
CON: sometimes hard to document and maintain. Be sure to clearly explain in header docs what each notification means and when it is sent.
KVO:
Similar concerns about NSNotifications;
CON: even more obscure to document. Be sure to add more header docs or architectural tips on your comments to explain who's listening what. I personally wouldn't use KVO for data loading or parsing tasks.
Personally, when dealing with network-enabled apps talking to a remote web service, I use a singleton data loader class (wrapping ASIHTTPRequest and handling all the serialization and deserialization) which pops notifications when something occurs. This way I can have the app delegate handling connection errors on its own (popping up alerts and such if required), and each controller only cares about the responses it wants.
Of course, this approach depends on the application, but this general architecture might be a starting point for your own code.

What is NSNotification?

Can anybody explain the importance of NSNotificationCenter?
Where to use them?
What is the difference between NSNotificationCenter vs. AppDelegate?
Apple has provided an Observer Pattern in the Cocoa library called the NSNotificationCenter.
The basic idea is that a listener registers with a broadcaster using some predefined protocol. At some later point, the broadcaster is told to notify all of its listeners, where it calls some function on each of its listeners and passes certain arguments along. This allows for asynchronous message passing between two different objects that don't have to know about one-another, they just have to know about the broadcaster.
You can find more details about it here: http://numbergrinder.com/node/32
The Application Delegate is an object which receives notifications when the UIApplication object reaches certain states. In many respects, it is a specialized one-to-one Observer pattern.
You can read more about it here: What is the AppDelegate for and how do I know when to use it?
If you come from an Actionscript background then NSNotification is like adding listeners to objects I guess.
NSNotification is like notifying the other class about the changes that will happen if some action takes place in another class.

NSNotificationCenter vs delegation( using protocols )?

What are the pros and cons of each of them?
Where should I use them specifically?
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.
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.
Notifications are generally better for notifying the UI of changes the occur on other threads as well. Apple's documentation strongly discourages the use of delegates across threads where possible, both for stability and performance reasons. On the Mac, they suggest using Bindings, but since they don't exist on the iPhone, notifications are probably your next best bet.
Considering the performance is a good idea (delegation better for small number of notified objects, notification centre better for larger number of objects, or is it? run a profiler) but I think a more important factor since you are talking about Objective-C and less likely to be talking about the really high performance parts of your code base, which are likely to be written in C, is reducing compile-time dependencies between modules.
There is nothing to stop you having an array of delegates rather than a single delegate.
I might use NSNotificationCenter only for status of any network stack components I make and any custom device status monitoring interfaces. But for most coupling, not to do with global status of the app, I think it is clearer to use normal interface contracts in Objective-C in most cases and easier to folow for the people coming after you than to use NSNotificationCenter. In fact I have never used NotificationCenter for my own custom events and prefer to use delegates for ease of code comprehension by someone else reading my code.
And finally, of course with notifications to/from the standard API you don't have choice and must use whichever of the two methods Apple proscribe for a given event.
Notifications are better for decoupling UI components. It allows you to plug any view without any modification in your controllers or models. Definitely better for loosely-coupled design.
But for the performance between delegation and notification, you need to think about the frequency of the call.
Delegation might be better for more frequent events, notifications are better for less frequent events but more recipients. It's up to project what to pick.
An option in between those two is using the observer pattern, without NSNotificationCenter. Look at my Objective-C implementation here.