NSNotificationCenter Best practices and list of active observers - iphone

I have been doing a great deal of work using Notifications in few of my apps, at first they gave me random crashes but then I learned about the best way to use NSNotifications and here are a few best practices that I learnt.
---remove the observe's when they are of no use.
---remove the observer's before they are deallocated, leads to random crashes.
---Do not add two observers methods in the same class for the same notification.
If I am wrong or If I miss anything feel free to add up. What I want now is when I post a notification can I see the list of observer's waiting to receive my notificaton and can I selectively post to a set of observer's by missing out some intentionally?.
I also saw this Thread that is quite similar. I am creating a new thread because I want to dig up more with Notifications. I expect good contributions.

Related

observer design pattern in rest aplications

I'm trying to learn design patterns, and I have come with the Observer pattern. I think I understand the concept itself, but I don't see when to use it.
I try to explain myself. I work mostly with web applications, so, stateless applications. Normally, the client makes a petition from the browser (for example, update a record). then the operation is completed.
Let us suppose that I want to notify some persons every time a record is updated. It seems to me the perfect scenario for the Observer patter, but when I think of it, it will end something like:
user makes petition of update.
get all the persons that have to be notified.
put all the persons that have to be notified in the observer.
make the update. (that also will make the notification for the observer pattern).
but... doing it this way, I have to iterate all the persons that I want to notify twice!
And because its a stateless application, I have to go and get all the persons than needs to be notified every time!
I don't know if the observer pattern is more useful for other types of applications, but I can only think of this pattern in a static form, I mean, making the Observer static.
I know I'm losing something, it's a common and accepted pattern, everyone accept it as a valid solution for this concrete problem. What I am not understanding?
First, let's straighten out the terminology.
Each person who wants to be notified is an Observer.
Each type of event which can trigger a notification is an Observable.
Each Observer (person) needs to register itself with the server. It sends a request essentially saying, "I'm interested in foo Observables," which in this case would be, "I'm interested in update events." The server maintains mappings of who is interested in which events.
Every time the server makes an update, it iterates over the mapping of update Observers and sends a notification to each of them.
The advantage is that the server and its Observables have no compile-time knowledge of who the Observers are. Observers are free to register (and unregister) themselves at runtime for any event(s) they are interested in.

Debugging/removing excess notifications

I have a lot of one-to-many notification needs in my app, so I'm constantly posting notifications for other objects to receive.
I was curious if anyone has a good method for debugging the contents of the default notification queue, aside from putting print statements in all my selectors. I'm sure I have a lot of functions that are called multiple times because I forget to remove them from the queue and add duplicates. I just need a good way to go through everything and figure out which ones are the culprits.

KVO rocks. Now how do I use it asynchronously?

I am sold on KVO but if used in the obvious way it is synchronous. I would like to use it in a situation where I am firing off many KVO messages in rapid succession and it is causing my app to grind to a halt as the KVO messages are handled. Can someone suggest an approach - perhaps using NSOperation or NSThread - that will work here?
My goal is to retain the decoupled, flexibility of KVO if possible.
KVO is inherently single threaded in that the KVO notifications will be delivered on the same thread as the change.
Of course, UIKit and Cocoa both really only want you to be diddling UI elements on the main thread.
Thus, if you are doing asynchronous operations, you are most likely using threads and, if so, already have a synchronization issue in that you need to get the notifs from some thread to the main thread.
And therein lies the key. Instead of blindly forwarding each change notification as it comes in, you can coalesce the change notifications before passing them on to the main thread.
There are a variety of means via which you can do this. The specific solution is going to be quite unique to your application, most likely.
Personally, I try to avoid coalesce-and-forward of fine grained operations. I find it far simpler to tell the main thread that a particular sub-graph of objects have changed. More likely than not, the drawing code that will then make the changes visible to the user is going to need to redraw related state and, thus, related changes will be automatically reflected.
The key, as you have surmised, is to throttle the notifications so you don't bog down app responsiveness (or destroy the devices battery life).
Use the Receptionist Pattern as recommended by Apple https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/ReceptionistPattern/ReceptionistPattern.html
Check out NSNotification. It's not quite the same thing, but you can fire off notifications on background threads (with a little bit of research and work). You can maintain the nice decoupling and fire-and-forget behavior.

Best practices for Singletons and Notifications on the iPhone

Just to give background for my situation, I have a manager singleton that pulls data from a webserver and provides access to the downloaded data. I have several types of views that will consume this data, but only one view at any time will need to receive events.
I was just wondering what people prefer to use when they need to get events from a singleton. Do you use NSNotificationCenter, Target/Action, or delegate?
Thanks for any help.
Are you really, really sure only one view needs to receive events? For instance, you don't have a master view that would need access to the same update that a subview was notified about?
If you truly have only one view controller needing updates at a time ever, I might use a delegate approach. Here's something to consider - what happens if you are in the middle of receiving an update and the user change screens... is that OK? would you cancel the request?
Anything more than one, or if that in-flight changing delegate scenario has issues, then you may well be better off with a notification that anyone can hook into. It's best to keep the notification light with some kind of reference to the change and have the receiver have to look up the altered data.
If there are going to be a large number of events, then you want to stay away from NSNotifications.
For the least amount of overhead I would go with the delegate pattern, although I don't think that target/action has much more overhead than delegates.
Try your favorite way and if there is a problem profile or try a different approach.
I usually start with the easiest to get implemented. For example I once tried to use notifications for some interface code I had written years ago but with 30-60 updates/second the whole interface bogged down unacceptably so I went with delegates which fixed the problem.

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.