没销毁通知,页面监听方法会走多次

2023-11-20  本文已影响0人  野咪咕

比如在 C页网络请求里面成功后想要B页刷新数据

在请求成功后发送通知

  [[NSNotificationCenter defaultCenter] postNotificationName:@"weixinSendAuthResp" object:resp];

在B页viewDidLoad方法里监听通知

- (void)viewDidLoad

{

    [super viewDidLoad];

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

}

//方法  一定要在dealloc方法里面移除所有通知,不然这个方法会执行多次,造成你判断出错

- (void)weixinSendAuthRespClick:(NSNotification *)center{

}


- (void)dealloc{

     // 移除当前控制器所有通知

    [[NSNotificationCenter defaultCenter] removeObserver:self];

//移除名为@"weixinSendAuthResp"的那个通知[[NSNotificationCenter defaultCenter]removeObserver:selfname:@"weixinSendAuthResp"object:nil];

}


实际中发现dealloc方法有时会不走,一般有以下三种原因可以参考排查

1. ViewController 中有Block,Block里面存在强引用;

2. ViewController 中有关的代理 ,delegate的属性应该用assign/weak修饰;

3. ViewController 中存在NSTimer ,计时器没有及时销毁;

找不到怎么办,还是不走dealloc方法

//那就在viewWillAppear 里面监听 在viewWillDisappear销毁通知

-(void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

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

}

//销毁通知

-(void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];

//移除名为@"weixinSendAuthResp"的那个通知

[[NSNotificationCenter defaultCenter]removeObserver:selfname:@"weixinSendAuthResp"object:nil];

   }

上一篇 下一篇

猜你喜欢

热点阅读