有人可以请告诉我一个例子的一个可可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 ];

一定要注销的通知(观察员)当你的目的是释放。苹果文件指出:"以前的对象是观察通知被释放,就必须告诉通知中心,以阻止它发送通知"。

对于本地通知下一代码是适用的:

[[NSNotificationCenter defaultCenter] removeObserver:self];

和观察员的分布通知:

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top