Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the recommended way for a model to communicate with a view controller?

For instance, I have a model class which handles receiving bluetooth messages from other iPhones. When I receive one of these messages, I need to update a view. I believe the standard way of doing this is through the view controller. The view controller has a reference to the model and the view, and so can communicate to each of them.

However how should they send messages back to the VC? They could have a reference to the view controller each (as an property, with assign not retain). Is that bad practise (if I'm not mistaken its a circular reference)?
Are there alternate ways of doing this? I've considered the delegate pattern, but to write an entire delegate and all seems like quite a lot of work for a simple problem. Alternatively, if you think I'm overthinking this, feel free to tell me!

[I think this question has probably come up before, it seems quite common, but I searched for a bit and didn't find much]

Thanks for your help,

like image 455
Tom H Avatar asked May 30 '11 09:05

Tom H


1 Answers

In general you have 3 different techniques:

  1. Delegation
  2. KVO (Key-Value Observing)
  3. Notifications

If your model only needs to inform one object (your view controller) of changes, delegation is the way to go. It may feel like extra work to create a new interface, add the delegate property to the model, etc. but it is definitely worth it in terms of flexibility, code reuse, design, etc. Delegation is a standard pattern in Cocoa programming and is used extensively in Apple's APIs.

If your model needs to inform multiple objects of changes, you want to use KVO or notifications. With KVO you can subscribe to change events for a specific property or key on the model. For example, when the 'messages' property on your model changes, any attached listeners can be notified of the change and respond accordingly.

Notifications are used when you want to send application-wide messages to multiple listeners. Examples from the standard APIs are keyboard notifications (when the keyboard is displayed/dismissed), and interface orientation changes.

So in your case, delegation or KVO would probably the best choice.

like image 194
Mike Weller Avatar answered Nov 15 '22 00:11

Mike Weller