NSNotificationCenter线程在第二次调用时中断,即使它已被删除

时间:2015-06-30 10:37:33

标签: ios objective-c ios8 nsnotificationcenter

我正在使用NSNotificationCenter用于两个不同的ViewControllers。第一次调用NSNotificationCenter效果很好,之后我删除了观察者。但是如果我再次运行它,那么在移除观察者之后线程就会中断。

ViewController1中的

 [[NSNotificationCenter defaultCenter] postNotificationName:@"textUpdateNotification" object: nil ];
ViewController2中的

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"textUpdateNotification" object:nil];

-(void)receiveNotification:(NSNotification *)notificaton
{
....
....
  [[NSNotificationCenter defaultCenter] removeObserver:self name:@"textUpdateNotification" object:nil];
}

我尝试移除- (void)dealloc中的观察者也发生了同样的事情。 enter image description here

2 个答案:

答案 0 :(得分:1)

尝试删除viewDidDisappear

中的观察者
-(void)viewDidDisappear:(BOOL)animated
{
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"textUpdateNotification" object:nil];
}

答案 1 :(得分:1)

抱歉我的错字, 我在源ViewController中移除观察者,我在触发NSNotification,我应该从第二个使用它的ViewController中删除它。

ViewController1中的

 [[NSNotificationCenter defaultCenter] postNotificationName:@"textUpdateNotification" object: nil ];
ViewController2中的

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"textUpdateNotification" object:nil];

    -(void)receiveNotification:(NSNotification *)notificaton
    {
    ....
    ....
      [[NSNotificationCenter defaultCenter] removeObserver:self name:@"textUpdateNotification" object:nil];
    }

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"textUpdateNotification" object:nil];
}

感谢每一个