NSNotificationCenter 重复注册

2017-07-14  本文已影响0人  speedsnail

对于某个方法被多次调用可能的问题

可以考虑是否是因为NSNotificationCenter重复注册通知或者注册的通知没有被及时移除。导致通知方法被多次执行
例如:

- (void)viewWillAppear:(BOOL)animated

{

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendNotificationAction:) name:@"myNotificate" object:nil]

}

在dealloc中注销观察者

-(void)dealloc{

[[NSNotificationCenterdefaultCenter]removeObserver:self name:@"myNotificate" object:nil];

}

由于添加观察者的类是单例,没有销毁每次当视图加载的时候,都会执行viewWillAppear方法,多次注册同一个观察者。但是视图消失的时候 dealloc中的注销观察没有执行,导致通知中的方法sendNotificationAction多次执行

解决方法:

在viewWillDisappear方法中移除观察者,使得添加观察者和移除观察者成对出现

-(void)viewWillDisappear:(BOOL)animated

{

[[NSNotificationCenterdefaultCenter]removeObserver:selfname: @"myNotificate"  object:nil];

}

上一篇下一篇

猜你喜欢

热点阅读