Search code examples
swiftipadmodel-view-controllersegueuisplitviewcontroller

How to share a datamodel between the master and detail of UISplitviewController?


I've got a DataModelController class which both the master and detail of my splitviewcontroller need to access simultaneously. The problem is that I can't just create an instance in each of them because I need the two data models to be the same.

I could create a DataModelController object in the master and then reference it in the detail but I don't know how to get access to it from code.

My architecture is:

                   / NavigationController (detail) - ViewController
Splitviewcontroller
                   \ NavigationController (master) - CollectionViewController

I'm using Xcode with Swift.

Since it was requested here is a minimal version of the code, detail:

class PageViewController: UIViewController {
    // I need to set this to the dataModelController of NotePreviewCollectionViewController
    var dataModelController: DataModelController!
}

and master:

class NotePreviewCollectionViewController: UICollectionViewController {
    let dataModelController = DataModelController()
}

Solution

  • The simplest way to share data is to let the data look after its own life cycle rather than tying it to the classes that use it.

    class DataModelController {
        static let instance = DataModelController()
        private init() {
        }
    }
    

    This way each class that needs the data model gets the one consistent version by referencing DataModelController.instance.