5

I have a problem to implementing the MVC pattern in iOS with Swift. According to the Apple documentation, there is a MVC schema:

MVC pattern

I am fine with that but as you can see, when the model changes itself (an incoming message from a socket, for exemple) how is it supposed to notify the controller?

For instance, I have a chat application with a model that represents a list of messages. When the model receives a new message, how does it notify the controller? Is there a conventional way to do that?

Thanks

4
  • 2
    The two most common ways are delegation and by using NSNotifications Commented May 31, 2016 at 20:55
  • @Paulw11 Yes, working perfectly and it's look beautiful, thanks! Commented May 31, 2016 at 21:26
  • 1
    Key value observing (kvo) is also a compelling way to solve this problem. NSHipster has an older but still interesting article on the matter: nshipster.com/key-value-observing Commented May 31, 2016 at 21:26
  • Agreed with @Paulw11.... Additionally, if there is potential for multiple interested parties, notifications are more flexible. Delegates often imply a one-to-one dependency that's only abstracted in theory. (There's also KVO, but the less said about that the better, perhaps. :) ) Commented May 31, 2016 at 21:30

2 Answers 2

3

You can achieve this Model - Controller communication in two ways.

  1. Delegate pattern
  2. Notifications (https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/index.html)

For detailed explanation I would recommend you to watch CS 193p MVC lecture. (https://www.youtube.com/watch?v=Cb8KtEI3ZaY)

Sign up to request clarification or add additional context in comments.

Comments

2

Communication between layers is a very interesting topic, and warrants more than just a list of methods.

Here is a very relevant article from objc.io that not only has an exhaustive list of communication methods, but also analyses their strength and weaknesses and suggests a flowchart to help you decide which method is best.

Making the Right Choice

In your case, the Model is the sender, and the Controller is the recipient. Usually, the controller holds the model, so the Controller knows the Model but the Model is ignorant of the Controller. You would therefore be in the lower part of the chart.

Please read the full article. It also has examples taken from Apple frameworks. It's really useful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.