Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to access in AppDelegate variable from the View controller?

Tags:

I would like to write in the text or csv (prefer) file the variable from the view controller.

Indeed I am doing a drawing app and I would like to write in the file the current position of the finger.

class ViewController: UIViewController {var lastPoint = CGPoint.zeroPoint ... } 

I would like to have access to lastPoint.x and lastPoint.y from the AppDelegate. how I could do that ? Thank you.

like image 863
Yann Amouyal Avatar asked Jun 23 '15 08:06

Yann Amouyal


People also ask

Is AppDelegate a controller?

The application delegate is a controller object. By default, it is the owner and controller of the main window -- which is a view -- in an iOS app.


2 Answers

Your question is full of confusion but if that's what you are looking for:

You can access the appDelegate by getting a reference to it like that:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 

after that if you have store a property called lastPoint in your appDelegate you can access its components very simply like that:

let x = appDelegate.lastPoint.x let y = appDelegate.lastPoint.y 

If you need to access your viewController properties from the AppDelegate, then I suggest having a reference to your view controller in your appdelegate:

var myViewController: ViewController! 

then when your view controller is created you can store a reference to it in the appdelegate property:

If your create your view controller outside of your appDelegate:

Swift 1-2 syntax

var theViewController = ViewController() let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.myViewController = theViewController 

Swift 3-4 syntax

var theViewController = ViewController() let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.myViewController = theViewController 

If you create your view controller inside of your appDelegate:

self.myViewController = ViewController() 

After that you can access your data from your viewcontroller from your appdelegate just by accessing its property like that:

let x = self.myViewController.lastPoint.x let y = self.myViewController.lastPoint.y 
like image 100
The Tom Avatar answered Nov 02 '22 23:11

The Tom


Swift 3 Update

    var theViewController = ViewController()     let appDelegate = UIApplication.shared.delegate as! AppDelegate     appDelegate.myViewController = theViewController 
like image 44
Sébastien REMY Avatar answered Nov 03 '22 01:11

Sébastien REMY