Cer
Cer

Reputation: 258

Static variable and function issue

The static variable always gives the same value. Why is not the function always called?

class SessionManager {
    static func AddSession(key : String, value : Any) {
        let session = UserDefaults.standard
        if session.object(forKey: key) != nil {
            session.removeObject(forKey: key)
        }
        session.setValue(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)        

    }

    static func GetSessionValue(key : String) -> Any? {
        let session = UserDefaults.standard
        return NSKeyedUnarchiver.unarchiveObject(with: session.value(forKey: key) as! Data)
    }

    static var CurrentEmployee : Employee? = SessionManager.GetSessionValue(key: CL.SESSION__CURRENT_EMPLOYEE) as? Employee

}

SessionManager.CurrentEmployee always is same.

Upvotes: 0

Views: 512

Answers (1)

Martin R
Martin R

Reputation: 539685

static var CurrentEmployee : Employee? = SessionManager.GetSessionValue(...) as? Employee

is a stored (type) property with an initial value which is evaluated exactly once, when the property is accessed the first time.

What you want is a computed property, with a getter which is evaluated on each access:

static var CurrentEmployee : Employee? { return SessionManager.GetSessionValue(...) as? Employee }

Self-contained example:

class Foo {

    static var currentNumber = 0

    static func nextNumber() -> Int {
        currentNumber += 1
        return currentNumber
    }

    static var storedProp = nextNumber()

    static var computedProp: Int { return nextNumber() }
}

print(Foo.storedProp) // 1
print(Foo.storedProp) // 1
print(Foo.storedProp) // 1

print(Foo.computedProp) // 2
print(Foo.computedProp) // 3
print(Foo.computedProp) // 4

print(Foo.storedProp) // 1

Upvotes: 2

Related Questions