Marin
Marin

Reputation: 531

Accessing a Running Instance of a Class Swift

I have class A in file A and class B in file B. In class B, I want to access the running instance of class A, in order to run a function located in it. Both classes are connected to view controllers. I do not want to create a new instance of class A as in classAInstance = classA(), but rather access the instance of class A that my app is already running. Any help would be appreciated.

Here is part of my code in class A:

Class A {
    func reloadTableView() {
        self.CardsTableView.reloadData()
    }
}

And here is part of my code in class B:

Class B {
    @IBAction func saveButton(_ sender: UIButton) {
        // here is where I want to call reloadTableView() from class A
    }
}

Upvotes: 0

Views: 683

Answers (1)

Morssel
Morssel

Reputation: 38

The quick and dirty method I might use would be where you have some singleton where you can store the current instances of your classes.

Example:

class EnvironmentUtility {
    
    private static var instance: EnvironmentUtility?
    
    internal class func shared() -> EnvironmentUtility {
        guard let currentInstance = instance else {
            instance = EnvironmentUtility()
            return instance!
        }
        return currentInstance
    }

    var myClassA: ClassA? = nil
    var myClassB: ClassB? = nil
}

Then in the viewDidLoad (Or wherever else you like that a new instance is being made) of the those ViewControllers/Classes:

class ClassA: UIViewController {
    …
    override func viewDidLoad()  {
    …
       EnvironmentUtility.shared().myClassA = self 
    }
    …
}

Later in ClassB you could then:

class ClassB: UIViewController {
    …
    @IBAction func saveButton(_ sender: UIButton)  {
       EnvironmentUtility.shared().myClassA.reloadTable()
    }
    …
 }

This isn’t the prettiest or Swifty-est way of doing it, but quick and dirty.

If you want to write a better solution I would suggest looking at the MVVM-C Swift architectural pattern (I use this pattern myself). In this architecture you will have access to a Coordinator that overseas viewController transitions and you can also track current instances of your ViewControllers/Classes in a much more elegant way.

Here is a crash course in MVVM-C: https://marcosantadev.com/mvvmc-with-swift/

Upvotes: 1

Related Questions