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

标签 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];

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

// in MyClass.h

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

但这很笨拙。将此类信息放在单独的文档中是唯一的选择吗?

最佳答案

这是我使用的:

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

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

在实现文件中:

   NSString * const ZZZSomeNotification = @"ZZZSomeNotification";

然后在您的代码中发布通知时,只要引用名称就使用 ZZZSomeNotification。

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

关于ios - 如何在头文件中记录 NSNotificationCenter 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994764/

相关文章:

ios - 如何设置重复本地通知的开始和结束时间?

ios - 将 RPPreviewController 中的视频保存到特定位置而不是保存到相机胶卷?

ios - 如何在 Xcode 中设置 SVN 存储库的用户名和密码?

ios - removeObserver 不工作

c++ - 有没有办法避免头文件中使用的 constexpr 函数在没有额外命名空间的情况下进入全局范围?

c - 如何排除pclint中的一些 "unable to open include file *.h"错误

objective-c - 如何正确切换到横向 View ?

iphone - UIActivityIndi​​catorView 卡住

ios - 如何在 Objective-C 中将字符串插入到 sqlite?

c++ - 为什么头文件 Head1.h 不能包含包含 Head1.h 的头文件 Head2.h?