如何在头文件中记录NSNotificationCenter通知

时间:2013-09-25 01:29:40

标签: ios header-files nsnotificationcenter foundation

我正在使用NSNotificationCenter类来广播我的应用模型以可能引起其他类感兴趣的方式发生变化。我正在遵循标准做法,如下:

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

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

那里没什么新东西。不过这是我的问题:我应该如何“声明”我发布的通知,以便其他开发人员知道要听什么?我并不是指字面上的声明,但除了编写单独的文档之外,我应该如何传达预期的内容呢?我希望有人使用我的类来查看头文件并确定他们可以期待的通知。我可以做这样的事......

// in MyClass.h

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

但那非常笨重。将这些信息放在单独的文档中是唯一的选择吗?

1 个答案:

答案 0 :(得分:2)

这是我使用的:

在头文件中,在#import行之后但在@interface声明之前:

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

在实施文件中:

   NSString * const ZZZSomeNotification = @"ZZZSomeNotification";

然后,当您在代码中发布通知时,请在引用名称时使用ZZZSomeNotification。

这与Apple在其头文件中声明通知名称的方式非常相似。通过Xcode"快速打开..."查看您使用的Apple提供的类的头文件。文件菜单中的菜单项,你会看到类似的东西。