Access class variable from any ViewController

67 Views Asked by At

I have this structure for my app:

  • I have a Realm DB that stores multiple Patient().

  • TabViewController with two childs: SearchViewController and DetailViewController

  • In SearchViewController there is a TableView.

  • I can select between multiples patients -Patient()- in TableView and store it in the same SearchViewController inside this variable: var chosenPatient = ChosenPatient()

The class ChosenPatient comes from the ModelController:

class ChosenPatient: NSObject {
    var data = Patient()
    { ... multiple functions ... }    
}

All I need in my updateLabels() of my SearchViewController is to access to:

label.stringValue = chosenPatient.data.name/lastName/age etc

But I want to do the same in my DetailsViewController. Simply I want to have a function updateLabels() that retrieve the SAME patient I have chosen in the SearchViewController and access all information that patient have.

I have read about NSNotifications, Delegates and Segues but I couldn't find a good explanatory method that could be adapted to my app scheme.

I want to have a GLOBAL variable with an unique Patient(), and access to the patient.data from any ViewController in a simple and concise way.

Regards :)

[Using XCODE 8.3, swift 3.2, app for macOS]

2

There are 2 best solutions below

0
nomadoda On BEST ANSWER

I would typically use a protocol-delegate pattern if it's a one-to-one relationship. You wouldn't want to keep any variable global unless absolutely necessary.

Make a custom class for your UITabBarController and assign SearchViewController to the DetailViewController dataSource.

protocol ChosenPatientDataSource: class {
    var chosenPatient: ChoosenPatient { get }
}

class SearchViewController: UITableViewController, ChosenPatientDataSource {
    var chosenPatient = ChosenPatient()
}

class DetailViewController: UIViewController {
    weak var dataSource: ChosenPatientDataSource?

    func useChosenPatient() {
        let chosenPatient = dataSource?.chosenPatient
        ...
    }
}

Hope it's to some help!

0
Mike Neilens On

To pass information between between views in different tabs such as your SearchViewController and DetailViewController I would use NSNotification.

I would strongly resist the temptation to fill up your app with lots of notifications as it quickly makes the code very hard to understand.