Question

I'm using the NSNotificationCenter class to broadcast when my app's model changes in a way that might interest another class. I'm following standard practice, something like this:

NSNumber *myData = [NSNumber numberWithInt:42];
NSDictionary *myDict =
            [NSDictionary dictionaryWithObject:myData
                                        forKey:@"data"];

NSString *myNotificationKey = @"mynote";
[[NSNotificationCenter defaultCenter] postNotificationName:myNotificationKey
                                                    object:self
                                                  userInfo:myDict];

Nothing new there. Here's my question, though: how should I "declare" the notifications I may post, so that other developers know what to listen for? I don't mean literally declare, but how should I communicate what to expect, aside from writing separate documentation? I'd like someone using my class to be able to look at the header file and determine what notifications they can expect. I could do something like this...

// in MyClass.h

/*
 * NOTIFICATIONS
 * Name: mynote
 * UserInfo: {data : (NSNumber *)}
 * Name: myothernote
 * etc....
 */

But that's pretty clunky. Is the only option to put such information in separate documentation?

Was it helpful?

Solution

Here's what I use:

in a header file, after #import lines but before the @interface declaration:

   // Documentation about why the notification is interesting and useful
   extern NSString * const ZZZSomeNameNotification;

in implementation file:

   NSString * const ZZZSomeNotification = @"ZZZSomeNotification";

Then when posting the notification in your code, use ZZZSomeNotification whenever referring to the name.

This is pretty similar to how Apple declares notification names in their header files. Take a look at the header file for an Apple-provided class that you use, via Xcode's "Open Quickly..." menu item in the File menu, and you will see something similar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top