Part of me thinks I understand the NSNotification concept. It's a centralized broadcast system with string based notifications. Post on one side, observe on one or multiple other sides and act accordingly. Another part of me though, the part that has to write the code, gets confused every time I need a notification. What piece of code goes into which header/implementation, what files actually do the observing and how do I keep it from becoming a mess? Time to straighten it out, will you help me verify these assumptions? I'm fairly confident up to number 4, but number 5 hits the confusion jackpot.
self
into the posting code: [[NSNotificationCenter defaultCenter] postNotificationName:@"note name" object:self]
. Correct?@"MenuItemTapped"
from A to B, and @"NavigateTo"
from B to C. Correct?NotificationNames.h
file, which would contain all the extern NSString *const NOTE_NAME
declarations. Yet that undermines the portability of a notification.#import
statements. How to minimize typo's, yet keep the constants/defines portable?You've mostly got it. Your numbers 1-3 are generally correct.
extern NSString *const UIKeyboardDidShowNotification
. In some private implementation file is the definition. A special note regarding your #4 above. Think of notifications as notifications, not as instructions. They usually capture state changes or broadly interesting events. "MenuItemTapped" is a reasonable thing to notify about, but "NavigateTo" usually isn't, because the implication is that you're telling some specific object to navigate somewhere. If that's the case, that object should probably be a delegate (or should be a property) of the thing that wants the navigation, and you should cause it to happen directly. This isn't a requirement, of course, and you can use the mechanism for whatever you want. But the Cocoa design patterns generally don't use notifications for "telling objects what to do", only for "telling whoever cares what will/did happen". Make sense?
Finally, specifically re: your examples in #4-- those sound like genuine UI events, and seem like the whole thing could be handled via delegation, unless there's some reason why those objects need to be so decoupled.