views:

33

answers:

1

I have a ContactsViewController which -whenever a row is selected- MessageViewController is opened (using pushViewController). Both the ContactsViewController and the MessageViewController 'register' to receive DatastoreDelegate messages. The weird thing is it all works fine upon loading of my application, but once I navigate to the MessageViewController the delegate methods on my ContactsViewController don't get called anymore. Both these controllers should handle the [messageAdded:(Message *)message] method, but only the MessageViewController keeps receiving the messages after it's been opened once.

Does anyone have any idea on how to make this work?

+1  A: 

In Cocoa, every object with a delegate has only one delegate (at any given time). That delegate is the only object that gets the delegate messages. There's no real concept of having "both objects registered to receive delegate messages." My suspicion here is that when you push the MessageViewController, it sets itself as the Datastore's delegate, and then the ContactsViewController never sees those messages again, because it doesn't set itself back.

I don't know how your code is structured, but you could simply hand-off the delegate every time the controllers change view so whichever is active is the current delegate.

In Cocoa, the Notification pattern (see NSNotificationCenter) is used when an object needs to "broadcast" information to multiple other objects. Delegates are really what they sound like: an object that another object optionally relies on to "partner with" it and provide key functionality. It's a more intimate relationship than a notification observer.

quixoto
Thanks, I was under the impression that delegates would be able to send messages to multiple classes, but I guess I was wrong with this assumption. I'll use the NotificationCenter or find a different way to implement my code.
Wolfgang Schreurs
Any object can send messages to multiple classes. Classes normally *aren't* delegates; you would normally only make an instance a delegate. And any object that has a delegate only has one delegate; two objects can't be its delegate at the same time. Use notifications if you want that.
Peter Hosey