NSNotifications name best practice

Rayfleck picture Rayfleck · Apr 21, 2011 · Viewed 9.7k times · Source

In trying to de-couple my model from the view controllers that display fetched data, when an asynchronous fetch completes, I post an NSNotification.

 [[NSNotificationCenter defaultCenter] postNotificationName:@"foobarFetchSuccess" object: foo];

I've gotten into the habit of using:

 #define FOO_FETCH_SUCCESS  @"foobarFetchSuccess"

in a common header file and then using it for the addObserver: and removeObserver: as well as the postNotificationName:

 [[NSNotificationCenter defaultCenter] addObserver:self @selector(gotData)
                                              name:FOO_FETCH_SUCCESS object: baz];

So @"foobarFetchSuccess" string is used all over the place. And there are many more just like him. So what's the best way to declare a string once and use it everywhere?

Answer

user557219 picture user557219 · Apr 21, 2011

As for using constant strings in your project, there’s another question on Stack Overflow about that: Constants in Objective C.

As for naming notifications, Coding Guidelines for Cocoa suggests the following:

Notifications are identified by global NSString objects whose names are composed in this way:

[Name of associated class] + [Did | Will] + [UniquePartOfName] + Notification