假設A與B之間進行通信,B來觸發事件,A接受該事件,並作出響應。
1) A編寫自定義的消息響應函數update
2) A向消息中心註冊,[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(update) name:@"update" object:nil]
3) B觸發事件[[NSNotificationCenter defaultCenter] postNotificationName:@"update" object:nil]
每壹個進程都有壹個默認的NSNotificationCenter,可以通過類方法defaultCenter獲取該消息中心的實例。消息中心可以處理同壹進程中不同對象之間的消息。如果要在同壹臺機器上進行進程間的通信,需要使用NSDistributedNotificationCenter。
消息中心以同步的方式將消息分發到所有的觀察者中,換言之,直到所有的觀察者都收到消息並處理完畢以後,控制權才會回到調用者的手裏。如果需要異步的處理消息,需要使用通知隊列NSNotificationQueue。
在多線程程序中,通知會被分發到每壹個發起消息的線程中,這可能與觀察者註冊時所在的線程已經不是同壹線程。
實例:
@implementation TestClass
- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (id) init
{
self = [super init];
if (!self) return nil;
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
return self;
}
- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}
@end