I have:
-
A delegate to handle a socket connection that reads and writes data to the socket.
-
A
MyTableViewControllerwith methods to fill a table in a view with data received from the socket.
My question is the following:
What would a valid design approach be to fill the table with data arriving at the socket?
(Given that in the future I will have several other views also using data from the socket.)
I thought I should have a single SocketClient class to handle all messages exchanged through the socket and then notify each relevant UIViewController. But, in this case, when data arrives at the socket, the controller object is already instantiated. Which led me to use the controller as a singleton. It works, but I don’t like this. An alternative would be for all my controllers to be delegates that handle the socket connection. I don’t like this either.
What would your approach be?
The correct approach here is called Model-View-Controller, and it’s the core architecture throughout Cocoa. The model holds your data (forget the socket for a moment; the tables don’t care where the data comes from). The (table)views display the data, and the (tableview)controllers connect the two.
So you would have a set of model objects that hold data. They don’t care about how the data is displayed and they don’t care where it comes from (the socket). They just hold the data. Sometimes these are managed by a Singleton, sometimes a pointer to the model is handed to each view controller when the view controllers are created. Either approach is fine. Handing the model to the view controllers is a little more flexible, but takes a little more code.
Then there is another object, your
SocketClient, that fetches data and updates the model. TheSocketClientdoes not hold the data. It just deals with the socket and updating the model. It knows nothing about the view controllers and they know nothing about it.Whenever the model changes, the view controllers are notified. This is most often handled via
NSNotification, but can also be handled via KVO or delegation.