views:

181

answers:

1

I'm going to be using NSNotifications in my app to decouple the code.

I want the compiler to help me when using strings as the names of the notifications, ie, if I mistype one, I want the compiler to tell me.

Using normal strings for this won't work, because the compiler won't know that if I typed "myNotificaion" that I really meant "myNotification".

One way to do this would be to use #defines, or const NSString variables, but that would mean they would have to be declared in a file, either the class they're originating from, or a globally included file.

The problem with having them declared in the class they originate from is that it will need to be included wherever the notifications are listened for, therefore creating a coupling that I don't want.

The problem with a global file is that it could possibly become long and messy and will contain lots of unrelated things.

Is there a way to accomplish this without this coupling or untidiness??

+1  A: 

No, not as far as I'm aware, #defines and NSString constants is where it's at and you can't get around having to include these in whatever file requires access to the string.

You could create header files for the different parts of your app, so you might have JJDocumentNotifications.h and JJViewNotifications.h for example. You could then #import them into your precompiled header (.pch) file, so the file looks something like this:

#import <Cocoa/Cocoa.h>
#import "JJDocumentNotifications.h"
#import "JJViewNotifications.h"

That way, the headers will automatically be included in all the files in your target and you won't need to import them specifically.

Rob Keniger
Yes, this is my current solution. It just seems rather adhoc... I was hoping there would be a more elegant way to do this :(
Jasarien
The biggest drawback to the NSString constants is that there are compiler warnings about "unused variables" if I only include the .h file to be able to send a single notification.
Jason Moore