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,
In general you have 3 different techniques:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With