Frage

I every time use dealloc for remove observer, but just faced with this link that describes that we can use viewWillDisapper instead of dealloc.

War es hilfreich?

Lösung 2

One critical thing about KVO is that you MUST match removeObserve and addObserver calls and you cannot add duplicate observers. This means that you must carefully think through where you add the observer and where you remove it so that you don't violate either of those restrictions.

If you add it in viewDidLoad it is currently sufficient to remove it in dealloc (since viewDidUnload isn't used any more), but the observer may trigger when the view isn't visible. If you're running on older OS'es where viewDidUnload is still called, this can also be problematic as you have to track when the observers are in place and when they aren't.

You can add it in viewDid/WillAppear, in which case you need to remove it in viewDid/WillDisappear. This is usually cleaner since the calls are (generally speaking) guaranteed to be matched up.

Andere Tipps

The choice is a matter of properly pairing the addObserver/removeObserver calls.

If you call addObserver in a place that is called once such as some init method or viewDidLoad then call removeObserver in dealloc.

If you call addObserver in a place that is called multiple times like viewWillAppear then call removeObserver in viewWillDisappear.

It's the proper pairing that matters.

The link you reference is relatively informative and accurate.

I think of it in these terms:

a) does the VC need to be notified while it's on screen only? use viewWillAppear/viewWillDisappear.

b)does the VC need to be notified as long as it's alive (but not necessarily on screen)? use init or viewDidLoad and remove in dealloc.

I've breakpointed my dealloc methods under ARC and they're called when expected. However viewDidUnload is not called.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top