有人能给我看一个Cocoa Obj-C对象的例子吗?它带有一个自定义通知,如何启动、订阅和处理它?

推荐答案

@implementation MyObject

// Posts a MyNotification message whenever called
- (void)notify {
  [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self];
}

// Prints a message whenever a MyNotification is received
- (void)handleNotification:(NSNotification*)note {
  NSLog(@"Got notified: %@", note);
}

@end

// somewhere else
MyObject *object = [[MyObject alloc] init];
// receive MyNotification events from any object
[[NSNotificationCenter defaultCenter] addObserver:object selector:@selector(handleNotification:) name:@"MyNotification" object:nil];
// create a notification
[object notify];

有关更多信息,请参阅NSNotificationCenter的文档.

Objective-c相关问答推荐

为何在Objective-C中,使用self.propName赋值会导致崩溃而使用_ivarName则不会?

Objective-c 点表示法或方括号表示法中首选什么?

如何检测 iPhone 5c 的 colored颜色 ?

Xcode 是否支持区域?

碰撞技术如何运作?

在Objective C中迭代枚举?

iOS - 应用程序关闭时的核心位置和地理围栏

动态转发: suppress Incomplete Implementation 警告

iOS - UITableViewCell 中 UIButton 的延迟Touch Down事件

iOS 7 状态栏与 NavigationBar 冲突

在 ObjC 实现文件中声明的实例变量

检测设备是否支持电话?

iPhone - 什么是重用标识符(UITableViewCell)?

从昨天开始无法将存档上传到应用store

WKWebView 判断 JavaScript 返回值

对 NSTimer 目标的弱引用以防止保留循环

获取最顶层的 UIViewController

根据文本量更改 UITableViewCell 高度

如何在 UITextField 上自动打开键盘?

使用 cocoaLumberjack 将日志(log)文件存储在哪里