NSNotificationCenter 重复注册

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

可以考虑是否是因为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];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容