What is the recommended way to connect the model to the controller?

For example, I have a model class that handles receiving Bluetooth messages from other iPhones. When I receive one of these messages, I need to update the view. I believe that the standard way to do this is through a view controller. The view controller has a link to the model and view, and therefore can communicate with each of them.

However, how should they send messages back to VC? They can have a link to the view controller each (as a property, with the purpose not to save). Is this bad practice (if I'm not mistaken for its round reference)?
Are there alternative ways to do this? I looked at the delegate template, but wrote a whole delegate, and everything seems to have quite a bit of work for a simple problem. Alternatively, if you think I'm thinking too much about it, feel free to tell me!

[I think this question probably came up earlier, seems pretty common, but I searched a bit and didn't find a lot]

Thanks for your help,

+6
source share
2 answers

In general, you have 3 different methods:

  • Delegation
  • KVO (monitoring of key values)
  • Notifications

If your model only needs to report one change object (your controller), delegation is the way to go. You may need additional work to create a new interface, add a delegate property to the model, etc., but it is definitely worth the flexibility, code reuse, design, etc. Delegation is a standard template in Cocoa programming and is widely used in the Apple API.

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

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

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

+6
source

I have never done this in an iOS application, but in general terms, mvc is sometimes better (and holds a code cleaner) to update the view directly from the yes model. This, in my opinion, is wonderful, but it combines the model with the idea that it is bad. So, to solve this problem, you must implement the observer design pattern (broadcast reception) (or use the built-in broadcast system / event receiver ios → NSNotificationCenter). Thus, when something happens that changes the model, the model will broadcast even, regardless of whether someone is listening to this event or not, this is not his problem, and therefore you separate the view from the model.

0
source

Source: https://habr.com/ru/post/889363/


All Articles