2022-03-07(通知:添加多次,执行多次)
2022-03-07 本文已影响0人
ImmortalSummer
对同一通知重复添加监听,监听方法会重复执行
- (void)addObserver{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationTestAction) name:@"kNotificationTest" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationTestAction) name:@"kNotificationTest" object:nil];
}
- (void)notificationTestAction{
NSLog(@"--> notificationTestAction");
}
/*
打印结果:
NSLog(@"--> notificationTestAction");
NSLog(@"--> notificationTestAction");
*/
无论添加多少次,只要移除一次即可:
- (void)addObserver{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationTestAction) name:@"kNotificationTest" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationTestAction) name:@"kNotificationTest" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationTestAction) name:@"kNotificationTest" object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"kNotificationTest" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationTestAction) name:@"kNotificationTest" object:nil];
}
- (void)notificationTestAction{
NSLog(@"--> notificationTestAction");
}
/*
打印结果:
NSLog(@"--> notificationTestAction");
*/