addObserver/removeObserver in viewWillAppear/viewWillDisappear

589 views Asked by At

I call addObserver in viewWillAppear and removeObserver in viewWillDisappear. It seems to work fine. However, in the Xcode crash logs I'm receiving reports that some customers crash when I call removeObserver (21 crashes yesterday...). I haven't had any customers report that they crash, so I assume this is relatively intermittent.

I read a suggestion to encapsulate the removeObserver call in a @try/@catch block, which I may resort to, but I'm curious as to why my removeObserver is failing. I assume it is because (somehow) the notification wasn't added. (Are there other reasons? I'm an iOS novice and new to crash logs...)

FWIW, I only call addObserver from one viewWillAppear and remove it in one viewWillDisappear. I've tried to duplicate the problem and never see (in NSLog messages) a call to viewWillDisappear without viewWillAppear first being called.

Thanks!

2

There are 2 answers

0
Srj0x0 On

Try to remove you observer in viewDidDissapeared. You can have problems with view controller life cycle.

0
Duncan C On

Calling addObserver in viewWillAppear, balanced by a call to removeObserver in viewWillDisappear should work.

Are you adding multiple individual observers in your viewWillAppear, and then removing all observers in viewWillDisappear? It's best to remove individual observers by name, as the system may use the notification center as well.