我正在使用 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/