2

How do you (if possible) create a class that anything that references it gets the same object?

So, if I had a LoginClass

and I dont want to create a new instance in each file but rather be able to just do

LoginClass.userID

in any file without first creating an instance of it?

user3916570
  • 780
  • 1
  • 9
  • 23

3 Answers3

1

It possible. Use singleton:

Stackoverflow question

Tutorial by Ray Wenderlich

Community
  • 1
  • 1
1

You are looking for a Singleton

This is the code

class Login {
    static let sharedInstance = Login()
    var userID: String?
    private init() {}
}

This is how you retrieve the same instance

Login.sharedInstance

And this is how you use it

Login.sharedInstance.userID = "123"

In a different point of your code...

 print(Login.sharedInstance.userID) // 123
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
1

Creating one instance per application life cycle means you want to implement Singleton pattern. You can implement singleton like this

class LoginManager {
    static let sharedInstance = LoginManager()

    var userId:String?
    var name:String?

}

And now you can use this like

LoginManager.sharedInstance.userId
Adnan Aftab
  • 14,377
  • 4
  • 45
  • 54