0

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.

0

1 Answer 1

2
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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.