1

In my application, a Connection object is initialized in my AppDelegate.swift, applicationDidBecomeActive().

How do I pass that Connection object to my ViewController subclass?

coiax
  • 462
  • 4
  • 19

2 Answers2

4
  • In AppDelegate create a property

    private weak var viewController : ViewController?
    
  • In the view controller in viewDidLoad assign self to that property

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.viewController = self
    

Now you can access the view controller from AppDelegate

vadian
  • 274,689
  • 30
  • 353
  • 361
  • What would be wrong with just accessing the connection from the ViewController, a la `let app_delegate = UIApplication.shared.delegate as! AppDelegate` and then `let connection = app_delegate.connection` – coiax Jan 14 '19 at 10:23
  • Of course you can do that, too. But you asked to pass the object from AppDelegate to the controller. And consider that the view controller could be instantiated sooner than `applicationDidBecomeActive()` is called. – vadian Jan 14 '19 at 10:24
  • I think I will probably do it the opposite way. But this was helpful in letting me know that I can access the AppDelegate singleton from UIApplication. – coiax Jan 14 '19 at 10:26
0

Instances like Connection are usually required throughout the application so the better idea is to create a shared instance of the required object and use anywhere we need.

class Connection{
  static let sharedConnection = Connection()
  ....
}

usage:

let connection = Connection.sharedConnection
Preetam Jadakar
  • 4,479
  • 2
  • 28
  • 58