iOS中通过通知中心可以实现发送与接收通知的效果,其中若多次发送同一通知,对方就会多次响应,但如果多次注册通知,也会有多次响应的效果,这里容易比较隐形的bug。
多次发送:
//发送通知方
//self
发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"justTest" object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"justTest" object:nil];
[[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");
[[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
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");
usingBlock:^(NSNotification *note) {
NSLog(@"luozhiwei");
}];
[[NSNotificationCenter
defaultCenter]
addObserverForName:@"justTest"
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
NSLog(@"luozhiwei");
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
2015-07-25 16:15:46.491 multipleRegistrationNotification[5233:171998] luozhiwei
结论:为了避免因此重复注册而造成错误,建议每次注册一个通知之前,可以先注销一次该通知。
本文探讨了在iOS应用中,如果多次发送或注册相同的通知,会导致接收方多次响应,产生潜在的bug。通过示例代码展示了通知发送与接收的场景,并指出为防止错误,应当在注册通知前先注销相同的通知。
174万+

被折叠的 条评论
为什么被折叠?



