NSNotificationCenter 通知,是一种开发设计模式。功能通常是由一个对象 A 发出通知,然后有多个对象 B,C,D... 等接收通知,并执行相关的操作,即由其他对象 B,C,D... 帮对象 A 完成事情。
注意事项:
1、一个对象发出通知(发出的通知,可带有参数),如:
NSNumber *tickerNumber = @(2);
NSString *message = @"帮我订购两张魔兽的电影票";
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:message, @"message", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"orderTicker" object:tickerNumber userInfo:dict];
2、多个对象接收通知(可解析通知中的参数信息内容),如:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderTicker:) name:@"orderTicker" object:nil];
- (void)orderTicker:(NSNotification *)notification
{
NSLog(@"name = %@", notification.name);
NSLog(@"object = %@", notification.object);
NSLog(@"userInfo = %@", notification.userInfo);
// NSLog(@"%@ 帮你订购了2张票", [self class]);
NSDictionary *dict = notification.userInfo;
NSString *message = [dict objectForKey:@"message"];
NSLog(@"%@ %@", [self class], message);
}
3、接收通知的对象必须实例化后才能响应接收通知,否则接收不了通知
4、接收通知的对象在释放后,必须注销通知,如:
- (void)dealloc
{
NSLog(@"%@ 注销通知", [self class]);
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
说明:
1、NSNotificationCenter 通知模式是一对多的,即一个对象发出的通知,可由多个已经实例化的对象接收并执行相关操作。
2、使用场景:
2-1、由其他对象协助完成其他事情
2-2、用于传值