Objective c Cocoa自定义通知示例

Objective c Cocoa自定义通知示例,objective-c,cocoa,notifications,Objective C,Cocoa,Notifications,有人能给我看一个Cocoa Obj-C对象的例子吗?它带有一个自定义通知,如何启动、订阅和处理它 @implementation MyObject // Posts a MyNotification message whenever called - (void)notify { [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self]; } // Prints a

有人能给我看一个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];

有关更多信息,请参阅。

步骤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");
}
//trigger event
[[NSNotificationCenter defaultCenter]
    postNotificationName:@"eventType"
    object:nil ];
第二步:

//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");
}
//trigger event
[[NSNotificationCenter defaultCenter]
    postNotificationName:@"eventType"
    object:nil ];

请确保在解除分配对象时取消注册通知(观察者)。苹果的文档说明:“在解除分配观察通知的对象之前,它必须通知通知中心停止向其发送通知”

对于本地通知,下一个代码适用:

[[NSNotificationCenter defaultCenter] removeObserver:self];
对于分布式通知的观察者:

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];

模糊的问题。试着问一个更具体的问题,或者搜索苹果的文档。我通常不会对这样的问题发表评论,但如果你收到一个“con”,那么我的可能是一个“pro”。这个问题可以给出一个简洁的答案,严格地回答这个问题。我只想找出一件简单的事情——不要浏览苹果的文档(无论如何,这很可能是值得的)。谢谢你提出这个问题。我看到你的+15自动取款机在这个问题上与我的观点一致。这是我写的一个应用程序,它可能会帮助你使用通知有什么意义?为什么不直接调用[object handleNotification]呢?松散耦合。请注意“//其他地方”注释。。。通知是一种广播消息。任何对象实例都可以侦听通知,不需要遵守任何特定的委托协议或类似协议。可能有许多实例在侦听单个消息。发送方不需要有指向它希望通知的对象实例的指针。