NSNotification does not reach all Observers
I use NSNotification
for a particular set of events. I have three views such that I have an "ADD" button on view 1 and clicking that makes me navigate from view 1 to view 2 to view 3 and again back to view 1.
1->2->3->1
I use NSNotification
s to push a view controller if the ADD button on view 1 is clicked, and I update the other views respectively, based on the notification posted by View 1.
When the notification is sent from view 1, only view 2 receives it. View 3 does not.
How is this possible? The code for observers is EXACTLY the same on view 2 and view 3.
This is the code for adding observers in view 2 and view 3:
[[NSNotificationCenter defaultCenter] addObserver:self
开发者_StackOverflow社区 selector:@selector(didPressAdd:)
name:@"DidAddNotification"
object:nil];
I also remove them in the dealloc()
function properly.
Navigating back to 1 using navigation controller will remove 2 and 3. So in dealloc, add a log saying that the particular controller has stopped listening. You shall see that the listener is being deallocated after which it won't listen to notifications. Updated the sample
to send a notification on return.
It's because viewDidLoad
and viewWillAppear:
are called after you send the notification. Set it up in initWithNibName:bundle:
instead (if you use xib files) or some other init
method if you don't (initWithCoder:
for example), assuming you have inited the controller somewhere. If you have not inited the controller, you can't really listen for notifications inside it either.
精彩评论