iOS/Cocoa - Design Pattern for Data Model <-> C

2019-02-20 09:58发布

问题:

(I have read many stackoverflow posts on this, and Cocoa MVC in general, but most relate to the sharing of information between View Controllers.)

Given the following:

  • a DataModel class responsible for the downloading, parsing, verification and storage of (XML or JSON derived) data,

  • a ViewController class, which will instantiate a single DataModel object, and will need to get information from that DataModel over time (e.g. updating views to reflect changes in the Model)

Q. What is the best practice for handling the notification of model data changes, and the supply of that data to the View Controller?

Approaches I've seen include:

  • the Model class posts Notifications, supplying the data in the Notification's userInfo dictionary. The View Controller listens for the Notifications, looks at the userInfo. e.g. Apple's SeismicXML sample code.

  • the Model class defines a Protocol, and the View Controller acts as the delegate, responding to specific protocol methods of the Model.

  • the Model class keeps a pointer to the View Controller, calls methods or properties in the View Controller directly. (Not a fan of this one, I must say, as it requires tight binding between the Model and Controller.)

I'm leaning towards the Notification approach, but would like to hear the views of other people.

回答1:

I would avoid at all costs having the model store pointers to the view controller. This is an inversion of the normal responsibilities. In MVC, the model should act independently of any controller.

The delegate/protocol pattern works well for short lived models that are created and destroyed within the lifecycle of the view controller.

Notifications and KVO are the primary way I handle underlying model changes. It allows for the model to live a long time and work independent of controllers that are created and destroyed during it's lifetime.



回答2:

If there's only one view controller class, and that class instantiates the model class, then a delegation approach is more appropriate. Notifications are better used when multiple classes need to get the information, or when the controllers are widely separated in the hierarchy from the model class, making it hard to get a proper reference to set the delegate.



回答3:

its not on your list, but Key-Value Observing could be useful for what you're doing. It would allow iOS to send the notifications for you.

You can read more about it here under the heading 'KVO'