iOS通過NSNotificationCenter來傳遞通告(Notification)的原理非常簡單彪标。
俗一點的原理如下:這個電線桿就是一個NotificationCenter. 誰都可以來發(fā)通告(Notification)残邀,誰都可以來看通告(Notification)。
雅一點的原理如下:
先講講俗的原理
電線桿上的牛皮癬廣告包含了至少三個參與方:
- 電線桿 (充當(dāng)NSNotificationCenter的角色)
- 有祖?zhèn)骼现嗅t(yī)的廣告張貼者 (充當(dāng)Poster的角色)
- 有祖?zhèn)髋Fぐ_的路人甲乙丙丁 (充當(dāng)Observer的角色)
發(fā)送notification(貼小廣告的來了)
方法一不用傳遞更多的信息,函數(shù)如下:
[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:nil];
方法二可以傳遞更多的信息,使用userInfo這個參數(shù)边器,函數(shù)如下:
// 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發(fā)送出來,必須要有相應(yīng)的observer來響應(yīng)這些notification, 并對這些notification采取響應(yīng)的措施托修。
方法一
// 添加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);
}
}];
移除
當(dāng)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];
參考文獻(xiàn):
iOS - 使用通知中心(NotificationCenter)進(jìn)行傳值
Notifications in iOS Part 1 – Broadcasting Events via NSNotificationCenter