iOS通過NSNotificationCenter來傳遞通告(Notification)的原理非常簡單。
俗一點的原理如下:這個電線桿就是一個NotificationCenter. 誰都可以來發通告(Notification),誰都可以來看通告(Notification)。

NotificationCenter
雅一點的原理如下:

學術一點
先講講俗的原理
電線桿上的牛皮癬廣告包含了至少三個參與方:
- 電線桿 (充當NSNotificationCenter的角色)
- 有祖傳老中醫的廣告張貼者 (充當Poster的角色)
- 有祖傳牛皮癬的路人甲乙丙丁 (充當Observer的角色)
發送notification(貼小廣告的來了)
方法一不用傳遞更多的信息,函數如下:
[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:nil];
方法二可以傳遞更多的信息,使用userInfo這個參數,函數如下:
// UserDataObject.h
@property (nonatomic, strong) NSString *property;
// Publisher.m
UserDataObject *userDataObject = [DataObject new];
userDataObject.property = @"This is property value";
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:userDataObject
forKey:@"additionalData"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification"
object:nil
userInfo:userInfo];
注冊Notification, 添加observer (看小廣告的來了)
上一步有notification發送出來,必須要有相應的observer來響應這些notification, 并對這些notification采取響應的措施。
方法一
// 添加observer
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(eventListenerDidReceiveNotification:)
name:@"MyNotification"
object:nil];
// 對notification采取的動作
- (void)eventListenerDidReceiveNotification:(NSNotification *)notification
{
if ([[notification name] isEqualToString:@"MyNotification"])
{
NSLog(@"Successfully received the notification!");
NSDictionary *userInfo = notification.userInfo;
UserDataObject *userDataObject = [userInfo objectForKey:@"additionalData"];
// Your response to the notification should be placed here
NSLog(@"userDataObject.property -> %@", userDataObject.property1);
}
}
方法二(采用了block)
self.observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"MyNotification" object:nil queue:nil usingBlock:^(NSNotification *notif) {
if ([[notif name] isEqualToString:@"MyNotification"])
{
NSLog(@"Successfully received the notification!");
NSDictionary *userInfo = notif.userInfo;
DataObject *dataObject = [userInfo objectForKey:@"additionalData"];
// Your response to the notification should be placed here
NSLog(@"dataObject.property1 -> %@", dataObject.property1);
}
}];
移除
當observer收到信息并完成操作后,不想再接收信息。
// If registered using addObserver:... method
[[NSNotificationCenter defaultCenter] removeObserver:self];
// If registered using addObserverForName:... method
[[NSNotificationCenter defaultCenter] removeObserver:self.observer];
self.observer = nil;
// You can also unregister notification types/names using
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"MyNotification" object:nil];
參考文獻:
iOS - 使用通知中心(NotificationCenter)進行傳值
Notifications in iOS Part 1 – Broadcasting Events via NSNotificationCenter