iOS中通过通知中心可以实现发送与接收通知的效果,其中若多次发送同一通知,对方就会多次响应,但如果多次注册通知,也会有多次响应的效果,这里容易比较隐形的bug。
多次发送:
//发送通知方
//self
发送通知
[[NSNotificationCenter
defaultCenter]
postNotificationName:@"justTest"
object:nil];
[[NSNotificationCenter
defaultCenter]
postNotificationName:@"justTest"
object:nil];
[[NSNotificationCenter
defaultCenter]
postNotificationName:@"justTest"
object:nil];
//接收通知方
- (void) resignNotification{
[[NSNotificationCenter
defaultCenter]
addObserverForName:@"justTest"
object:nil
queue:nil
usingBlock:^(NSNotification
*note) {
NSLog(@"luozhiwei");
}];
}
结果:
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
多次接收:
//发送通知方
[[NSNotificationCenter
defaultCenter]
postNotificationName:@"justTest"
object:nil];
//接收通知方
- (void) resignNotification{
[[NSNotificationCenter
defaultCenter]
addObserverForName:@"justTest"
object:nil
queue:nil
usingBlock:^(NSNotification
*note) {
NSLog(@"luozhiwei");
}];
[[NSNotificationCenter
defaultCenter]
addObserverForName:@"justTest"
object:nil
queue:nil
usingBlock:^(NSNotification
*note) {
NSLog(@"luozhiwei");
}];
[[NSNotificationCenter
defaultCenter]
addObserverForName:@"justTest"
object:nil
queue:nil
usingBlock:^(NSNotification
*note) {
NSLog(@"luozhiwei");
}];
}
结果:
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
结论:为了避免因此重复注册而造成错误,建议每次注册一个通知之前,可以先注销一次该通知。