views:

90

answers:

3

Here is something I just can't get to work....I can make the view controller talk to my custom objects just fine....but how do I send messages to the View Controller from my objects?

A message from myViewController to myObject would look like [myObject doSomething].

What would the opposite message look like? Does it even make sense to send a message the other way?

Greatly appreciate your help!

+2  A: 

You could pass a controller to a model, but often you want models to not depend on views or controllers.

To avoid that, make a protocol that the model wants to talk to and have the view controller implement it and have the model take an instance of the protocol, not the view controller as a property.

Lou Franco
+1  A: 

Why would you want your model to actively talk to anything in the first place? View controllers are the active managers of the app flow, and initiate communications to the model, not the other way around.

Can you say a more specific example of a situation where you would actually need to do this?

Like you suspect yourself, most of the time it doesn't make sense to send messages “the other way.” But if you really need to do that, an appropriate way to broadcast information “out” from models is notifications. You can have your model send notifications, and view controllers or any other objects can subscribe to those notifications if they care, but there is no tight coupling from model to other app pieces.

Jaanus
Many thanks Jaanus....this is what I was wondering. I noticed apple using the term notifications in their documentation. I will check out your link. Many thanks to you and all the others for their answers!
Ben
+2  A: 

I often use NSNotificationCenter to broadcast updates from model objects to interested controllers. For a more tightly bound interaction, consider making a delegate protocol for the model object.

A notification is mostly one way, although the listener could access the model object that sent the notification. There can be any number of interested parties, including none if controllers come and go but the model is persistent.

A delegate is two way, but there can only be one delegate at a time. Usually a delegate is expected to outlive the object it is a delegate to. A delegate might be good for a phase of a model object lifespan that requires extra user input.

Notifications and delegates can be used simultaneously. As with UIApplication, the delegate is usually called before the notification is sent.

drawnonward