0

In swift, how to create a variable in the app delegate in order to retrieve it everywhere in the app? I am not talking about NSManagedObject

I know that it begin with :

let appDelegate = UIApplication.shared.delegate as! AppDelegate

I have a class Personne

class Personne {
var One: String
var Two: Float
}

and another classe to create a Singleton:

class PersonneController {
var shared = Personne()

and in my app, i have created an instance like this:

var personne = Personne()

so every variable is retrieving by

personne.shared.myvariable

How to put personne in the app delegate, in order to retrieve it from everywhere?

Wahib
  • 93
  • 1
  • 8
  • 1
    "in order to retrieve it everywhere in the app" tempting as that may be, you definitely don't want that. Something mutable that can be accessed from anywhere can be changed from anywhere, which means that you can't easily read any of the code that access the value. Your local reasoning makes you think some code should behave in one way, but it can do totally other things because other modules can be accessing and changing that global value under your feet. It becomes a nightmare real easily – Alexander Nov 21 '20 at 23:58
  • 1
    @Alexander-ReinstateMonica in general you are right, except that the solution i have adopted is different. here is the link that explain it very well. [link](https://code.tutsplus.com/tutorials/the-right-way-to-share-state-between-swift-view-controllers--cms-28474) – Wahib Nov 22 '20 at 00:22
  • @Monica you were really close. What you are looking for is called [Singleton](https://developer.apple.com/documentation/swift/cocoa_design_patterns/managing_a_shared_resource_using_a_singleton) and check this [post](https://stackoverflow.com/a/47481780/2303865) as well – Leo Dabus Nov 22 '20 at 16:31

3 Answers3

1

1 . Create the instance of your "Personne" Class in AppDelegate ( var persnee = Personne())

2 . create a function in your AppDelegate to which will return instance of AppDelegate

class func appDelegate() -> AppDelegate {

return UIApplication.shared.delegate as! AppDelegate

}

3 . You can call like this

AppDelegate.appDelegate(). persnee

vinay
  • 132
  • 8
0

Inside the class

class AppDelegate..... {
  var name:String?
}

Then

let appDelegate = UIApplication.shared.delegate as! AppDelegate 
print(appDelegate.name)

But for this it's better to make a singleton class like

class Service {
  static let shared = Service()
  var name:String?
}

Then

print(Service.shared.name)

or even make it a global variable

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
-1
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.blabla
Melih Sevim
  • 930
  • 6
  • 9