Cocoa自定义通知示例如何设置?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (31)

有人能告诉我一个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

用户回答回答于

步骤1:

//register to listen for event    
[[NSNotificationCenter defaultCenter]
  addObserver:self
  selector:@selector(eventHandler:)
  name:@"eventType"
  object:nil ];

//event handler when event occurs
-(void)eventHandler: (NSNotification *) notification
{
    NSLog(@"event triggered");
}

步骤2:

//trigger event
[[NSNotificationCenter defaultCenter]
    postNotificationName:@"eventType"
    object:nil ];

扫码关注云+社区

领取腾讯云代金券