Question

I have a case where the child view sends notification to its parent view. Now I'm calling addObserver: in viewWillAppear: and removeObserver: in viewWillDisappear:. But, I'm guessing this is not correct since viewWillAppear: calls when view is refreshed.

[[NSNotificationCenter defaultCenter] addObserver: (id)observer selector: (SEL)aSelector name: (NSString *)aName object: (id)anObject];

[[NSNotificationCenter defaultCenter] removeObserver: (id)observer name: (NSString *)aName object: (id)anObject];

Thanks.

Was it helpful?

Solution

Actually, this is a bad idea. When memory gets low, your view controller may get sent a memory warning. The default behavior in this instance is to clear out your view (if you're not currently on screen). In this case, you could get the viewDidLoad message sent a second time (after the memory event, when your view is brought back on screen by its navigation controller.) Thus you'll have two registrations of the same object, but only one removal (in its dealloc)

A better solution is either to set a flag saying you've registered, or to register in your init method.

OTHER TIPS

I guess the correct positions to register for notification is viewDidLoad method, and correct position to unregister for same notifications is dealloc method.

Ben's right - but I found another, potentially fragile, way around that. I just discovered this because I was forever getting the "...was deallocated while key value observers were still registered with it"

I don't know why - but when I had addObserver in my init method, and removeObserver in my dealloc method - I was still getting the KVO was still being observed message. I stepped through and verified that my removeObserver was being called correctly.

I moved my addobserver into the viewDidLoad method instead, and that seemed to work.

I left a removeObserver in viewDidUnload and in dealloc; but I don't like that because it's not balanced. But under normal circumstances, my viewDidUnload doesn't get called - this is just protection in case I get a low memory notification.

But I can see potentially getting into the situation where a low memory event comes in, viewDidUnload gets called. If I then hit dealloc sometime after that (before I hit viewDidLoad again), I will call removeObserver twice!

So, I think I'll just keep it in my viewDidLoad, and my dealloc.

I still don't know why it doesn't work right if I do the addobserver in my init method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top