Tometoyou Tometoyou - 6 months ago 13
iOS Question

How does this function/variable work?

I'm using the following code to retrieve

NSURLCredentials
:

let credentials: NSURLCredential? = {
let loginProtectionSpace = NSURLProtectionSpace(host: host, port: 0, protocol: NSURLProtectionSpaceHTTP, realm: nil, authenticationMethod: NSURLAuthenticationMethodDefault)
let credentials = NSURLCredentialStorage.sharedCredentialStorage().defaultCredentialForProtectionSpace(loginProtectionSpace)
return credentials
}()


This is called when the user opens the app. The credentials returned are nil. Then I set these credentials and try to print credentials out again and it's still nil. However, if I restart the app, the printed credentials are there. What's going on here?

Answer

This is a lazy variable. The code gets executed once when you first access the property. After that the initially returned value is "remembered" and returned on future calls.

If you set the credentials yourself in the NSURLCredentialStorage then on the next start of the app the first access of the property once again executes the code and retrieves the stored credentials. Note that during the run where you first set the credentials up the actual 3 lines of code retrieving the credentials from the storage are not executed a second time and therefore during that run of the app the property still is nil while there actually is a value in the storage. A similar thing will happen if you modify the existing credentials - during the run where you change them, the credentials will still hold a reference to the previous ones.

If you want to be able to requery the store, you should either