美文网首页
2022-03-07(通知:添加多次,执行多次)

2022-03-07(通知:添加多次,执行多次)

作者: ImmortalSummer | 来源:发表于2022-03-07 12:07 被阅读0次

对同一通知重复添加监听,监听方法会重复执行

- (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");
*/

相关文章

网友评论

      本文标题:2022-03-07(通知:添加多次,执行多次)

      本文链接:https://www.haomeiwen.com/subject/fstnrrtx.html